Compare commits

..

1 Commits

Author SHA1 Message Date
claude[bot] d8cb7313db feat(cli): add orphans command to show entities without relations
Adds a new `basic-memory orphans` CLI command that identifies entities
with no incoming or outgoing connections in the knowledge graph, helping
users discover isolated notes that haven't been linked into their knowledge base.

Changes:
- EntityRepository.find_without_relations(): efficient SQL EXISTS subquery
- GET /v2/projects/{id}/knowledge/orphans API endpoint
- OrphanEntitiesResponse schema (entities list + total count)
- KnowledgeClient.get_orphans() typed API client method
- `basic-memory orphans` CLI command with table and --json output
- Tests for repository method, API endpoint, and CLI command

Closes #762

Co-authored-by: Paul Hernandez <phernandez@users.noreply.github.com>
Signed-off-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
2026-04-23 02:13:55 +00:00
160 changed files with 3491 additions and 16060 deletions
+1 -4
View File
@@ -10,9 +10,6 @@ on:
# - "src/**/*.js"
# - "src/**/*.jsx"
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
jobs:
claude-review:
# Only run for organization members and collaborators
@@ -30,7 +27,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
fetch-depth: 1
+2 -5
View File
@@ -4,9 +4,6 @@ on:
issues:
types: [opened]
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
jobs:
triage:
runs-on: ubuntu-latest
@@ -15,7 +12,7 @@ jobs:
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
fetch-depth: 1
@@ -71,4 +68,4 @@ jobs:
Read the issue carefully and provide helpful triage with appropriate labels.
claude_args: '--allowed-tools "Bash(gh issue:*),Bash(gh search:*),Read"'
claude_args: '--allowed-tools "Bash(gh issue:*),Bash(gh search:*),Read"'
+2 -4
View File
@@ -12,9 +12,6 @@ on:
pull_request_target:
types: [opened, synchronize]
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
jobs:
claude:
if: |
@@ -44,7 +41,7 @@ jobs:
actions: read # Required for Claude to read CI results on PRs
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
# For pull_request_target, checkout the PR head to review the actual changes
ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.head.sha || github.sha }}
@@ -68,3 +65,4 @@ jobs:
# See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
# or https://docs.claude.com/en/docs/claude-code/sdk#command-line for available options
# claude_args: '--model claude-opus-4-1-20250805 --allowed-tools Bash(gh pr:*)'
+3 -6
View File
@@ -5,9 +5,6 @@ on:
branches: [main]
workflow_dispatch: # Allow manual triggering
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
jobs:
dev-release:
runs-on: ubuntu-latest
@@ -16,12 +13,12 @@ jobs:
contents: write
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Python
uses: actions/setup-python@v6
uses: actions/setup-python@v5
with:
python-version: "3.12"
@@ -53,4 +50,4 @@ jobs:
uses: pypa/gh-action-pypi-publish@release/v1
with:
password: ${{ secrets.PYPI_TOKEN }}
skip-existing: true # Don't fail if version already exists
skip-existing: true # Don't fail if version already exists
+6 -6
View File
@@ -9,7 +9,6 @@ on:
env:
REGISTRY: ghcr.io
IMAGE_NAME: basicmachines-co/basic-memory
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
jobs:
docker:
@@ -20,17 +19,17 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
uses: docker/setup-buildx-action@v3
with:
platforms: linux/amd64,linux/arm64
- name: Log in to GitHub Container Registry
uses: docker/login-action@v4
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
@@ -38,7 +37,7 @@ jobs:
- name: Extract metadata
id: meta
uses: docker/metadata-action@v6
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
@@ -49,7 +48,7 @@ jobs:
type=raw,value=latest,enable={{is_default_branch}}
- name: Build and push Docker image
uses: docker/build-push-action@v7
uses: docker/build-push-action@v5
with:
context: .
file: ./Dockerfile
@@ -59,3 +58,4 @@ jobs:
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
+2 -5
View File
@@ -7,14 +7,11 @@ on:
- edited
- synchronize
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
jobs:
main:
runs-on: ubuntu-latest
steps:
- uses: amannn/action-semantic-pull-request@v6
- uses: amannn/action-semantic-pull-request@v5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
@@ -41,4 +38,4 @@ jobs:
deps
installer
# Allow breaking changes (needs "!" after type/scope)
requireScopeForBreakingChange: true
requireScopeForBreakingChange: true
+22 -62
View File
@@ -5,9 +5,6 @@ on:
tags:
- 'v*' # Trigger on version tags like v1.0.0, v0.13.0, etc.
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
jobs:
release:
runs-on: ubuntu-latest
@@ -16,12 +13,12 @@ jobs:
contents: write
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Python
uses: actions/setup-python@v6
uses: actions/setup-python@v5
with:
python-version: "3.12"
@@ -42,7 +39,7 @@ jobs:
echo "Build completed successfully"
- name: Create GitHub Release
uses: softprops/action-gh-release@v3
uses: softprops/action-gh-release@v2
with:
files: |
dist/*.whl
@@ -63,63 +60,26 @@ jobs:
# Only run for stable releases (not dev, beta, or rc versions)
if: ${{ !contains(github.ref_name, 'dev') && !contains(github.ref_name, 'b') && !contains(github.ref_name, 'rc') }}
permissions:
contents: read
contents: write
actions: read
steps:
# Inline bump replaces mislav/bump-homebrew-formula-action@v4.x.
# The action does a HEAD request to api.github.com /repos/.../tarball/<ref>
# with the bearer token and expects a 302 redirect. GitHub now returns
# 303 on that endpoint when authenticated, which the action treats as a
# fatal error. Re-implementing the bump as plain git+sed keeps the same
# contract (update url + sha256, commit, push) with no third-party action.
- name: Update Homebrew formula
uses: mislav/bump-homebrew-formula-action@v3
with:
# Formula name in homebrew-basic-memory repo
formula-name: basic-memory
# The tap repository
homebrew-tap: basicmachines-co/homebrew-basic-memory
# Base branch of the tap repository
base-branch: main
# Download URL will be automatically constructed from the tag
download-url: https://github.com/basicmachines-co/basic-memory/archive/refs/tags/${{ github.ref_name }}.tar.gz
# Commit message for the formula update
commit-message: |
{{formulaName}} {{version}}
Created by https://github.com/basicmachines-co/basic-memory/actions/runs/${{ github.run_id }}
env:
HOMEBREW_TOKEN: ${{ secrets.HOMEBREW_TOKEN }}
REF: ${{ github.ref_name }}
REPO: ${{ github.repository }}
RUN_URL: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
# Personal Access Token with repo scope for homebrew-basic-memory repo
COMMITTER_TOKEN: ${{ secrets.HOMEBREW_TOKEN }}
VERSION="${REF#v}"
ARCHIVE_URL="https://github.com/${REPO}/archive/refs/tags/${REF}.tar.gz"
echo "::group::Compute tarball sha256"
SHA256="$(curl --fail --silent --location "$ARCHIVE_URL" | sha256sum | awk '{print $1}')"
test -n "$SHA256"
echo "sha256: $SHA256"
echo "::endgroup::"
echo "::group::Clone tap"
git clone \
--depth 1 \
"https://x-access-token:${HOMEBREW_TOKEN}@github.com/basicmachines-co/homebrew-basic-memory.git" \
tap
cd tap
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
echo "::endgroup::"
echo "::group::Patch Formula/basic-memory.rb"
# Pipe-delimited sed because the URL contains slashes. The Formula
# only has one `url` and one `sha256` directive, so a first-match
# replacement is unambiguous. POSIX character classes ([[:space:]])
# keep this portable across BSD and GNU sed.
sed -i -E \
-e "s|^([[:space:]]*url[[:space:]]+)\"[^\"]+\"|\1\"${ARCHIVE_URL}\"|" \
-e "s|^([[:space:]]*sha256[[:space:]]+)\"[^\"]+\"|\1\"${SHA256}\"|" \
Formula/basic-memory.rb
git --no-pager diff Formula/basic-memory.rb
echo "::endgroup::"
if git diff --quiet Formula/basic-memory.rb; then
echo "Formula already at ${REF}; nothing to do."
exit 0
fi
echo "::group::Commit & push"
git add Formula/basic-memory.rb
git commit -m "basic-memory ${VERSION}
Created by ${RUN_URL}"
git push origin HEAD:main
echo "::endgroup::"
+20 -23
View File
@@ -11,9 +11,6 @@ on:
# Outcome: each branch push runs the test suite once, including PR updates.
push:
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
jobs:
static-checks:
name: Static Checks (Python 3.12)
@@ -21,12 +18,12 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v4
with:
submodules: true
- name: Set up Python 3.12
uses: actions/setup-python@v6
uses: actions/setup-python@v4
with:
python-version: "3.12"
cache: "pip"
@@ -35,7 +32,7 @@ jobs:
run: |
pip install uv
- uses: extractions/setup-just@v4
- uses: extractions/setup-just@v3
- name: Create virtual env
run: |
@@ -55,7 +52,7 @@ jobs:
test-sqlite-unit:
name: Test SQLite Unit (${{ matrix.os }}, Python ${{ matrix.python-version }})
timeout-minutes: 45
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
@@ -71,12 +68,12 @@ jobs:
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v4
with:
submodules: true
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v6
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
cache: 'pip'
@@ -85,7 +82,7 @@ jobs:
run: |
pip install uv
- uses: extractions/setup-just@v4
- uses: extractions/setup-just@v3
- name: Create virtual env
run: |
@@ -117,12 +114,12 @@ jobs:
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v4
with:
submodules: true
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v6
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
cache: 'pip'
@@ -131,7 +128,7 @@ jobs:
run: |
pip install uv
- uses: extractions/setup-just@v4
- uses: extractions/setup-just@v3
- name: Create virtual env
run: |
@@ -147,7 +144,7 @@ jobs:
test-postgres-unit:
name: Test Postgres Unit (Python ${{ matrix.python-version }})
timeout-minutes: 60
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
@@ -174,12 +171,12 @@ jobs:
BASIC_MEMORY_TEST_POSTGRES_URL: postgresql://basic_memory_user:dev_password@127.0.0.1:5432/basic_memory_test
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v4
with:
submodules: true
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v6
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
cache: 'pip'
@@ -188,7 +185,7 @@ jobs:
run: |
pip install uv
- uses: extractions/setup-just@v4
- uses: extractions/setup-just@v3
- name: Create virtual env
run: |
@@ -231,12 +228,12 @@ jobs:
BASIC_MEMORY_TEST_POSTGRES_URL: postgresql://basic_memory_user:dev_password@127.0.0.1:5432/basic_memory_test
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v4
with:
submodules: true
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v6
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
cache: 'pip'
@@ -245,7 +242,7 @@ jobs:
run: |
pip install uv
- uses: extractions/setup-just@v4
- uses: extractions/setup-just@v3
- name: Create virtual env
run: |
@@ -265,12 +262,12 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v4
with:
submodules: true
- name: Set up Python 3.12
uses: actions/setup-python@v6
uses: actions/setup-python@v4
with:
python-version: "3.12"
cache: "pip"
@@ -279,7 +276,7 @@ jobs:
run: |
pip install uv
- uses: extractions/setup-just@v4
- uses: extractions/setup-just@v3
- name: Create virtual env
run: |
-34
View File
@@ -56,15 +56,6 @@ Run `just test-smoke` when you specifically need the MCP smoke flow.
If testmon is “cold,” the first run may be long. Subsequent runs get much faster.
### PR CI Gate
Before opening or updating a PR, run the checks that mirror the common required CI failures:
- Run `just typecheck` in addition to targeted `ruff` and `pytest` commands when tests were added or changed.
- Sign commits with `git commit -s` so DCO passes. If a PR branch already has unsigned commits, rewrite the branch with signed-off commits before asking for review.
- Use a semantic PR title accepted by `.github/workflows/pr-title.yml`: `type(scope): summary`.
- Use one of the allowed scopes: `core`, `cli`, `api`, `mcp`, `sync`, `ui`, `deps`, `installer`.
### Test Structure
- `tests/` - Unit tests for individual components (mocked, fast)
@@ -253,31 +244,6 @@ async_client.set_client_factory(your_custom_factory)
See SPEC-16 for full context manager refactor details.
### Release Process
Releases are driven by `just release` / `just beta` — never by a bare `git tag`. The recipes bump version metadata, run pre-flight checks, commit, tag, and push. GitHub Actions then publishes to PyPI and updates the Homebrew formula.
**Stable release:**
```
just release v0.21.3
```
The recipe runs `just lint` + `just typecheck`, then updates `__version__` in `src/basic_memory/__init__.py` and `"version"` in `server.json` (MCP registry metadata), commits as `chore: update version to X.Y.Z for vX.Y.Z release`, creates the `vX.Y.Z` tag, and pushes both the commit and the tag to `origin/main`. After the tag lands, the `Release` workflow builds the package, publishes to PyPI, creates the GitHub release with auto-generated notes, and updates the Homebrew formula. The recipe finishes by printing the post-release tasks the workflow doesn't cover.
**Beta release:** `just beta v0.21.3b1` — same flow with a beta-suffixed tag. PyPI consumers install with `pip install basic-memory --pre`.
**Development builds:** every commit to `main` publishes a `0.21.3.dev26+468a22f`-style version to PyPI automatically via `.github/workflows/dev-release.yml`. No human action.
**Do not tag releases by hand.** A bare `git tag vX.Y.Z` skips the in-code version bump. Package metadata is still correct (uv-dynamic-versioning derives it from the git tag) but `basic-memory --version` reports the previous release, which is what happened with v0.21.2 → v0.21.3.
**Post-release tasks** the recipe surfaces but doesn't run:
- `docs.basicmemory.com` — add notes to `src/pages/latest-releases.mdx`
- `basicmachines.co` — bump version in `src/components/sections/hero.tsx`
- MCP Registry — `mcp-publisher publish` from the repo root
See `.claude/commands/release/release.md` (and `beta.md`, `release-check.md`, `changelog.md` alongside it) for the full release + post-release runbook, including the slash commands.
## BASIC MEMORY PRODUCT USAGE
### Knowledge Structure
+6 -153
View File
@@ -1,153 +1,6 @@
# CHANGELOG
## v0.21.5 (2026-05-26)
Workspace/project routing fixes for MCP, plus a SQLite vector reindex stability fix.
### Bug Fixes
- **#854**: MCP project listing now keeps duplicate cloud project rows distinct by
workspace, so only the selected workspace row inherits local project state.
- **#853**: `write_note` returns workspace-qualified permalinks for cloud
workspace writes, allowing follow-up `memory://` reads to route back to the
correct workspace/project.
- **#852**: Full SQLite vector reindex now loads `sqlite-vec` before dropping
`vec0` virtual tables, preventing reindex crashes.
- **#838**: Local ASGI database initialization is preloaded so MCP routing can
safely enter local project contexts.
## v0.21.1 (2026-05-16)
CI-only release. No user-facing changes.
### Maintenance
- **#833**: Replace `mislav/bump-homebrew-formula-action` with an inline
bash bump step. The action's `resolveRedirect` HEAD-requests
`api.github.com /repos/.../tarball/<ref>` expecting HTTP 302; GitHub now
returns 303 for authenticated requests on that endpoint, which broke
the v0.21.0 Homebrew job and required a manual tap bump. The inline
step does the same work (curl + sha256sum, clone tap, sed-bump
`url`/`sha256`, commit, push) without any third-party dependency.
## v0.21.0 (2026-05-16)
Workspace-aware everywhere: every MCP tool and CLI command now routes through the
same workspace/project model, the search and sync paths are noticeably faster,
and a handful of long-standing parsing and routing footguns are gone.
### Breaking Changes
- Relation parsing no longer treats unquoted multi-word text before a wikilink as a
custom relation type. Use single-token relation types like `relates_to [[Target]]`,
or quote multi-word relation types like `"relates to" [[Target]]` or
`'relates to' [[Target]]`.
- Bare list wikilinks like `- [[Target]]` now index as `links_to`.
- Prose list items like `- some other thing [[Target]]` now index as `links_to`.
- To preserve existing multi-word relation types on re-sync, quote them before upgrading.
- See **#824**.
### Features
- **#816**: `bm orphan` CLI command surfaces entities whose underlying markdown
files are gone, with a flag to clean them out.
- **#789**: Create projects directly by cloud workspace slug from MCP
(`create_memory_project(workspace=...)`).
- **#757**: Discover projects across every accessible cloud workspace in MCP's
project list — no more per-workspace blind spots.
- **#766**: MCP tools accept training-data-friendly parameter aliases
(`q`/`search`/`text` for `query`, etc.) so models reach for them naturally.
- **#776**: `bm db reset` refuses to run while a `basic-memory mcp` process is
alive, so resets can no longer corrupt an open session.
- **#791**: Search responses include result totals so pagers can stop guessing.
- **#719**: Cloud `note_content` tenant schema primitive lands on the backend.
- **#715**: `bm project add` accepts a `--visibility` flag for cloud projects.
### Bug Fixes
#### Search and recent activity
- **#832**: SQLite project deletion now sweeps `search_index`,
`search_vector_chunks`, and `search_vector_embeddings`, so a project that
reuses a recycled auto-increment id can't inherit the previous tenant's content.
- **#812**: `recent_activity` orders and filters by `updated_at`, so edits bubble
to the top instead of staying pinned to creation time.
- **#807**: Multi-project `search_notes` is opt-in (`search_all_projects=True`);
default search stays scoped to the resolved project.
- **#785**: `recent_activity` caps responses and emits an explicit truncation
footer instead of silently dropping rows.
- **#713**: Eliminated an N+1 query in search result hydration.
#### Workspace / project routing
- **#822**: `bm project list` now includes projects from every workspace, not
just the current one.
- **#813**, **#808**, **#806**, **#803**, **#801**, **#795**, **#790**, **#778**,
**#777**, **#722**, **#712**, **#704**: Workspace-qualified permalink routing
is centralized and applied consistently across `edit_note`, `delete_project`,
`build_context`, `memory://` URLs, factory-mode project listing, cloud uploads,
and the API client.
#### Sync
- **#827**: `rclone bisync` filters from `.bmignore` are preserved across syncs.
- **#815**: Watch service ignores hidden paths relative to the watched project,
not just relative to `$HOME`.
- **#814**: `scan` subprocesses no longer go through the shell, avoiding quoting
issues with paths that contain special characters.
- **#759**: Watch service stays inside `--project` scope.
- **#746**: Canonical markdown is preserved during single-file sync.
#### Parsing
- **#796**: Picoschema modifier descriptions (`field?(modifier, description)`)
parse correctly.
- **#769**: Obsidian callout blocks are skipped by the observation parser
instead of being mis-extracted as observations.
#### CLI
- **#775**: `bm project set-cloud` / `set-local` cleans up local DB state for
the affected project.
- **#773**: `bm cloud logout` clears `default_workspace`.
- **#780**: `bm cloud setup` hint points at `bm cloud sync-setup`.
- **#734**: `bm project info` shows cloud index freshness.
- **#718**: Private cloud projects display under their `display_name` instead of
raw UUID.
- **#768**: `read_note` / `view_note` drop no-op pagination params from their
signatures.
#### Stability
- **#774**: `sqlite-vec` failures during init degrade gracefully to keyword-only
search instead of crashing startup.
- **#733**: Delete-vector and cloud-sync cleanup is now consistent.
- **#702**: Race conditions in concurrent `delete_entity` are resolved.
- **#724**: `external_id` is preserved when entities are re-upserted during a
re-index.
- **#728**: Vector init no longer issues runtime `ALTER TABLE`.
- **#744**: `BASIC_MEMORY_CONFIG_DIR` is honored across remaining call sites.
- **#743**: FastEmbed cache lives under the data dir instead of `/tmp`.
- **#752**: Cloud projects report `source=cloud` in factory mode.
- Stripped null bytes from markdown content before DB insert.
- Allowed long `relation_type` values in API responses.
#### Installer
- **#772**: Docker-compose config volume mounts under the `appuser` home.
- **#695**: Bumped `brew outdated` timeout from 15s to 60s.
### Performance
- **#828**: CLI startup no longer pulls in the local ASGI FastAPI app when it
isn't needed.
- **#751**, **#726**, **#717**, **#714**, single-file/batch indexing: marked
speedups on the sync hot path; unchanged markdown is skipped entirely.
- **#731**, **#723**: Vector sync is faster on both backends, with tuned
fastembed defaults.
### Maintenance
- **#825**: Dependency refresh + security hardening.
- Updated to `fastmcp` 3.3.1.
- **#754**: Removed in-house telemetry wrappers in favor of direct `logfire`
usage.
- **#736**: `ty` is now the default typechecker.
- **#771**, **#770**, **#716**: New regression guards for vector-row cleanup,
long relation types, and recent activity hydration.
## Unreleased
## v0.20.3 (2026-03-26)
@@ -2272,12 +2125,12 @@ Signed-off-by: phernandez <paul@basicmachines.co>
- Update CLAUDE.md ([#33](https://github.com/basicmachines-co/basic-memory/pull/33),
[`dfaf0fe`](https://github.com/basicmachines-co/basic-memory/commit/dfaf0fea9cf5b97d169d51a6276ec70162c21a7e))
fix spelling in CLAUDE.md: environment typo Signed-off-by: Ikko Eltociear Ashimine
fix spelling in CLAUDE.md: enviroment -> environment Signed-off-by: Ikko Eltociear Ashimine
<eltociear@gmail.com>
### Refactoring
- Move project stats into project subcommand
- Move project stats into projct subcommand
([`2a881b1`](https://github.com/basicmachines-co/basic-memory/commit/2a881b1425c73947f037fbe7ac5539c015b62526))
Signed-off-by: phernandez <paul@basicmachines.co>
@@ -2706,7 +2559,7 @@ Co-authored-by: phernandez <phernandez@basicmachines.co>
### Bug Fixes
- Refix virtual env in installer build
- Refix vitual env in installer build
([`052f491`](https://github.com/basicmachines-co/basic-memory/commit/052f491fff629e8ead629c9259f8cb46c608d584))
@@ -2725,7 +2578,7 @@ Co-authored-by: phernandez <phernandez@basicmachines.co>
### Bug Fixes
- Fix path to installer app artifact
- Fix path to intaller app artifact
([`53d220d`](https://github.com/basicmachines-co/basic-memory/commit/53d220df585561f9edd0d49a9e88f1d4055059cf))
@@ -2733,7 +2586,7 @@ Co-authored-by: phernandez <phernandez@basicmachines.co>
### Bug Fixes
- Activate virtualenv in installer build
- Activate vitualenv in installer build
([`d4c8293`](https://github.com/basicmachines-co/basic-memory/commit/d4c8293687a52eaf3337fe02e2f7b80e4cc9a1bb))
- Trigger installer build on release
+34
View File
@@ -224,6 +224,40 @@ See `test-int/BENCHMARKS.md` for detailed benchmark documentation.
- **Fixtures**: Use async pytest fixtures for setup and teardown
- **Markers**: Use `@pytest.mark.benchmark` for benchmarks, `@pytest.mark.slow` for slow tests
## Release Process
Basic Memory uses automatic versioning based on git tags with `uv-dynamic-versioning`. Here's how releases work:
### Version Management
- **Development versions**: Automatically generated from git commits (e.g., `0.12.4.dev26+468a22f`)
- **Beta releases**: Created by tagging with beta suffixes (e.g., `git tag v0.13.0b1`)
- **Stable releases**: Created by tagging with version numbers (e.g., `git tag v0.13.0`)
### Release Workflows
#### Development Builds
- Automatically published to PyPI on every commit to `main`
- Version format: `0.12.4.dev26+468a22f` (base version + dev + commit count + hash)
- Users install with: `pip install basic-memory --pre --force-reinstall`
#### Beta Releases
1. Create and push a beta tag: `git tag v0.13.0b1 && git push origin v0.13.0b1`
2. GitHub Actions automatically builds and publishes to PyPI
3. Users install with: `pip install basic-memory --pre`
#### Stable Releases
1. Create and push a version tag: `git tag v0.13.0 && git push origin v0.13.0`
2. GitHub Actions automatically:
- Builds the package with version `0.13.0`
- Creates GitHub release with auto-generated notes
- Publishes to PyPI
3. Users install with: `pip install basic-memory`
### For Contributors
- No manual version bumping required
- Versions are automatically derived from git tags
- Focus on code changes, not version management
## Creating Issues
If you're planning to work on something, please create an issue first to discuss the approach. Include:
+577 -452
View File
File diff suppressed because it is too large Load Diff
+2 -67
View File
@@ -8,71 +8,6 @@
## Reporting a Vulnerability
If you find a vulnerability, please contact hello@basicmachines.co.
Use this section to tell people how to report a vulnerability.
Please do not open a public GitHub issue for security vulnerabilities. We aim
to respond within 72 hours and will coordinate a fix and disclosure timeline
with you.
## Threat Model
Basic Memory is a local-first MCP server that reads and writes markdown files
inside configured project directories. It runs on your machine with your user
permissions, so local configuration deserves the same care as any other
developer tool that can access your files.
### What Basic Memory Controls
- Filesystem-touching tools validate paths against the configured project root
with `validate_project_path()`, resolved paths, and `Path.is_relative_to()`.
Path traversal attempts such as `../../etc/passwd` are blocked at this layer.
- Scan optimizations in `sync_service.py` call `find` through
`asyncio.create_subprocess_exec()` with explicit argument lists. Project paths
are passed as data, not interpolated into shell strings.
- Auto-update code uses hardcoded commands, list-form arguments, and
`stdin=DEVNULL`. User-controlled strings do not reach a shell there.
### MCP Client-Side Risk
Recent MCP ecosystem research has highlighted a client-side pattern where an
MCP host can be configured to run arbitrary commands as "servers." That risk is
in the host configuration, not in notes or Basic Memory tool input.
The recommended Basic Memory MCP configuration uses a known command with
explicit arguments:
```json
{
"mcpServers": {
"basic-memory": {
"command": "uvx",
"args": ["basic-memory", "mcp"]
}
}
}
```
Only add MCP server entries from sources you trust. Avoid inline shell scripts
or command strings copied from untrusted sources. Treat third-party MCP server
configuration with the same scrutiny as any locally executed program.
Related ecosystem context:
- OX Security: The Mother of All AI Supply Chains
- CSO Online: RCE by design: MCP architectural choice haunts AI agent ecosystem
### Out Of Scope
- Basic Memory does not execute note content as code. Notes are returned as
data to the LLM.
- Basic Memory does not open network ports by default. The MCP server uses
stdio; the optional REST API is intended for localhost use.
- Basic Memory is designed for single-user local knowledge bases and does not
implement access controls between operating-system users.
## Secure Configuration Checklist
- MCP config `command` points to `uvx` or a trusted binary, not a shell string.
- Project paths in Basic Memory config come from trusted local configuration.
- If exposing the REST API, bind it only to localhost.
- Review any third-party MCP servers before adding them to your host config.
If you find a vulnerability, please contact hello@basicmachines.co
+2 -5
View File
@@ -1,8 +1,5 @@
# Docker Compose configuration for Basic Memory with PostgreSQL
# Use this for local development and testing with Postgres backend.
#
# The Postgres backend requires the pgvector extension (semantic search).
# This image bundles pgvector; plain postgres:17 will not work for vector search.
# Use this for local development and testing with Postgres backend
#
# Usage:
# docker-compose -f docker-compose-postgres.yml up -d
@@ -10,7 +7,7 @@
services:
postgres:
image: pgvector/pgvector:pg17
image: postgres:17
container_name: basic-memory-postgres
environment:
# Local development/test credentials - NOT for production
+1 -3
View File
@@ -17,9 +17,7 @@ services:
volumes:
# Persistent storage for configuration and database
# Container runs as `appuser` (Dockerfile USER directive), so the CLI
# config dir lives under /home/appuser, not /root.
- basic-memory-config:/home/appuser/.basic-memory:rw
- basic-memory-config:/root/.basic-memory:rw
# Mount your knowledge directory (required)
# Change './knowledge' to your actual Obsidian vault or knowledge directory
+7 -25
View File
@@ -106,7 +106,7 @@ The parser excludes these list item patterns:
|---------|---------|--------|
| Checkboxes | `- [ ] Todo item`, `- [x] Done`, `- [-] Cancelled` | Task list syntax |
| Markdown links | `- [text](url)` | URL link syntax |
| Bare wiki links | `- [[Target]]` | Treated as a `links_to` relation instead |
| Bare wiki links | `- [[Target]]` | Treated as a relation instead |
A list item with `#tags` but no `[category]` is still parsed — the tags are extracted and the category defaults to `Note`.
@@ -116,65 +116,47 @@ Relations connect documents to form the knowledge graph. There are two kinds.
### Explicit Relations
Written as list items with a relation type and a `[[wiki link]]` target. Unquoted
relation types are single tokens. Quote relation types that contain spaces.
Written as list items with a relation type and a `[[wiki link]]` target.
**Syntax:**
```
- relation_type [[Target Entity]] (context)
- "multi word relation type" [[Target Entity]] (context)
- 'multi word relation type' [[Target Entity]] (context)
```
| Part | Required | Description |
|------|----------|-------------|
| `relation_type` | Yes | Single unquoted token before `[[`, or quoted text for multi-word labels. |
| `relation_type` | No | Text before `[[`. Defaults to `relates_to` if omitted. |
| `[[Target]]` | Yes | Wiki link to the target entity. Matched by title or permalink. |
| `(context)` | No | Parenthesized text after `]]`. Supporting details. |
### Examples
Explicit relations:
```markdown
- implements [[Search Design]]
- depends_on [[Database Schema]]
- works_at [[Y Combinator]] (co-founder)
- "based on" [[Customer Interview]]
- 'in response to' [[Incident Review]]
```
Bare wiki links and prose list items create implicit `links_to` relations:
```markdown
- [[Some Entity]]
- some other thing [[Some Entity]]
```
Both examples above create `links_to [[Some Entity]]`. Use quotes when the words before
`[[` are meant to be a multi-word relation type.
The last example — a bare `[[wiki link]]` in a list item — gets relation type `relates_to`.
Common relation types:
- `implements`, `depends_on`, `relates_to`, `inspired_by`
- `extends`, `part_of`, `contains`, `pairs_with`
- `works_at`, `authored`, `collaborated_with`
Any single-token text or quoted text works as a relation type. These are conventions,
not a fixed set.
Any text works as a relation type. These are conventions, not a fixed set.
### Inline References
Wiki links appearing in regular prose create implicit `links_to` relations. This includes
list items that do not match the explicit relation grammar above.
Wiki links appearing in regular prose (not as list items) create implicit `links_to` relations.
```markdown
This builds on [[Core Design]] and uses [[Utility Functions]].
- We should revisit [[Search Design]] after the API changes.
```
This creates three relations: `links_to [[Core Design]]`, `links_to [[Utility Functions]]`,
and `links_to [[Search Design]]`.
This creates two relations: `links_to [[Core Design]]` and `links_to [[Utility Functions]]`.
### Forward References
+1 -41
View File
@@ -91,11 +91,10 @@ SQLite Database (Index)
# List all projects
projects = await list_memory_projects()
# Response structure (each entry includes external_id you can pass as project_id):
# Response structure:
# [
# {
# "name": "main",
# "external_id": "550e8400-e29b-41d4-a716-446655440000",
# "path": "/Users/name/notes",
# "is_default": True,
# "note_count": 156,
@@ -103,7 +102,6 @@ projects = await list_memory_projects()
# },
# {
# "name": "work",
# "external_id": "9f86d081-884c-42a3-b5e3-1c0c5b4c8e52",
# "path": "/Users/name/work-notes",
# "is_default": False,
# "note_count": 89,
@@ -166,44 +164,6 @@ active_project = "main"
results = await search_notes(query="topic", project=active_project)
```
### `project` vs `project_id`
Every project has two identifiers:
- **`project`** — human-readable name (e.g., `"main"`). Easy to use, but can collide across cloud workspaces.
- **`project_id`** — stable `external_id` UUID. Always unambiguous; takes precedence over `project` when both are passed.
**When to prefer `project_id`:**
1. **Cloud multi-workspace setups.** If the user belongs to more than one workspace (personal + organization, or several organizations) and the same project name might exist in more than one of them, pass `project_id` to route to the exact project. Without it, name resolution falls back to the default workspace, which may not be the one the user means.
2. **After `list_memory_projects()`.** Once you have the `external_id`, prefer using it — it's the same number of characters in JSON and saves a name-resolution round-trip.
3. **When persisting a project choice across a long session.** UUIDs are stable; names can be renamed.
**When `project` (name) is fine:**
- Local single-workspace setups (no collision risk).
- One-off operations where the name is clearly visible to the user (e.g., quick `search_notes(project="main", ...)`).
- The user explicitly references a project by name in their message.
**Example — cloud multi-workspace pattern:**
```python
# Discover and pick the right project for this user
projects = await list_memory_projects()
target = next(p for p in projects if p["name"] == "research" and p["workspace"]["slug"] == "acme")
# Use the UUID for all subsequent operations — no ambiguity
await write_note(
title="Meeting Notes",
content="...",
folder="meetings",
project_id=target["external_id"],
)
results = await search_notes(query="kickoff", project_id=target["external_id"])
```
**Precedence rule:** When both are passed, `project_id` wins. This lets you safely supply `project="main"` for backward compatibility while still routing precisely with `project_id`.
### Cross-Project Operations
**Some tools work across all projects when project parameter omitted:**
+76 -155
View File
@@ -1,6 +1,6 @@
# Basic Memory Cloud CLI Guide
The Basic Memory Cloud CLI provides seamless integration between local and cloud knowledge bases using **project-scoped synchronization**. Personal workspaces can optionally use local rclone mirrors, giving you fine-grained control over what syncs and where.
The Basic Memory Cloud CLI provides seamless integration between local and cloud knowledge bases using **project-scoped synchronization**. Each project can optionally sync with the cloud, giving you fine-grained control over what syncs and where.
## Overview
@@ -8,13 +8,9 @@ The cloud CLI enables you to:
- **Authenticate cloud access** - OAuth/API key credentials are stored locally for cloud operations
- **Project-scoped sync** - Each project independently manages its sync configuration
- **Explicit operations** - Sync only what you want, when you want
- **Bidirectional sync** - Keep Personal workspace local mirrors and cloud in sync with rclone bisync
- **Bidirectional sync** - Keep local and cloud in sync with rclone bisync
- **Offline access** - Work locally, sync when ready
Team workspaces are accessed through the cloud API/MCP and do not support local
multi-user rclone sync/bisync. Use `bm project list --workspace <workspace>` to
inspect Team projects.
## Prerequisites
Before using Basic Memory Cloud, you need:
@@ -43,7 +39,7 @@ If you attempt to log in without an active subscription, you'll receive a "Subsc
**Projects can exist in three states:**
1. **Cloud-only** - Project exists on cloud, no local copy
2. **Cloud + Local (synced)** - Personal workspace project has a local working directory that syncs
2. **Cloud + Local (synced)** - Project has a local working directory that syncs
3. **Local-only** - Project exists locally and is not routed to cloud
**Example:**
@@ -59,8 +55,8 @@ bm project add work --cloud --local-path ~/work-notes
bm project add temp --cloud # No local sync
# Now you can sync individually (after initial --resync):
bm cloud bisync --name research
bm cloud bisync --name work
bm project bisync --name research
bm project bisync --name work
# temp stays cloud-only
```
@@ -91,28 +87,23 @@ Apply OSS discount code `{{OSS_DISCOUNT_CODE}}` during checkout to receive 20% o
### 2. Set Up Sync
Install rclone and configure Personal workspace sync credentials:
Install rclone and configure credentials:
```bash
bm cloud setup
```
**What this does:**
1. Installs rclone with a supported package manager (if needed)
1. Installs rclone automatically (if needed)
2. Fetches your tenant information from cloud
3. Generates scoped S3 credentials for sync
4. Configures single rclone remote: `basic-memory-cloud`
**Result:** You're ready to sync Personal workspace projects. No sync directories created yet - those come with project setup.
Rclone setup uses package managers such as Homebrew, MacPorts, apt, dnf, yum, pacman,
zypper, snap, winget, Chocolatey, or Scoop when available. It does not run remote
install scripts with `sudo`; if no supported package manager is found, the CLI prints
manual install instructions.
**Result:** You're ready to sync projects. No sync directories created yet - those come with project setup.
### 3. Add Projects with Sync
Create Personal workspace projects with optional local sync paths:
Create projects with optional local sync paths:
```bash
# Create cloud project without local sync
@@ -122,7 +113,7 @@ bm project add research --cloud
bm project add research --cloud --local-path ~/Documents/research
# Or configure sync for existing project
bm cloud sync-setup research ~/Documents/research
bm project sync-setup research ~/Documents/research
```
**What happens under the covers:**
@@ -141,10 +132,10 @@ Establish the initial sync baseline. **Best practice:** Always preview with `--d
```bash
# Step 1: Preview the initial sync (recommended)
bm cloud bisync --name research --resync --dry-run
bm project bisync --name research --resync --dry-run
# Step 2: If all looks good, run the actual sync
bm cloud bisync --name research --resync
bm project bisync --name research --resync
```
**What happens under the covers:**
@@ -171,7 +162,7 @@ This will effectively make both Path1 and Path2 filesystems contain a matching s
After the first sync, just run bisync without `--resync`:
```bash
bm cloud bisync --name research
bm project bisync --name research
```
**What happens:**
@@ -239,13 +230,13 @@ bm project add research --cloud --local-path ~/Documents/research
- Stores sync config in `~/.basic-memory/config.json`
- Prepares for bisync (but doesn't sync yet)
**Result:** Project ready to sync. Run `bm cloud bisync --name research --resync` to establish baseline.
**Result:** Project ready to sync. Run `bm project bisync --name research --resync` to establish baseline.
**Use case 3: Add sync to existing cloud project**
```bash
# Project already exists on cloud
bm cloud sync-setup research ~/Documents/research
bm project sync-setup research ~/Documents/research
```
**What this does:**
@@ -296,24 +287,20 @@ For MCP stdio, routing is always local.
## File Synchronization
Local rclone sync/bisync is supported only for Personal workspaces. Team
workspaces are cloud-only for local CLI usage; access them through cloud API/MCP
routing instead of a local multi-user rclone mirror.
### Understanding the Sync Commands
**There are three sync-related commands:**
1. `bm cloud sync` - One-way: local → cloud (make cloud match local)
2. `bm cloud bisync` - Two-way: local ↔ cloud (recommended)
3. `bm cloud check` - Verify files match (no changes)
1. `bm project sync` - One-way: local → cloud (make cloud match local)
2. `bm project bisync` - Two-way: local ↔ cloud (recommended)
3. `bm project check` - Verify files match (no changes)
### One-Way Sync: Local → Cloud
**Use case:** You made changes locally and want to push to cloud (overwrite cloud).
```bash
bm cloud sync --name research
bm project sync --name research
```
**What happens:**
@@ -335,10 +322,10 @@ bm cloud sync --name research
```bash
# First time - establish baseline
bm cloud bisync --name research --resync
bm project bisync --name research --resync
# Subsequent syncs
bm cloud bisync --name research
bm project bisync --name research
```
**What happens:**
@@ -357,7 +344,7 @@ echo "Local change" > ~/Documents/research/notes.md
# Cloud now has: "Cloud change"
# Run bisync
bm cloud bisync --name research
bm project bisync --name research
# Result: Newer file wins (based on modification time)
# If cloud was more recent, cloud version kept
@@ -374,7 +361,7 @@ bm cloud bisync --name research
**Use case:** Check if local and cloud match without making changes.
```bash
bm cloud check --name research
bm project check --name research
```
**What happens:**
@@ -386,7 +373,7 @@ bm cloud check --name research
```bash
# One-way check (faster)
bm cloud check --name research --one-way
bm project check --name research --one-way
```
### Preview Changes (Dry Run)
@@ -394,7 +381,7 @@ bm cloud check --name research --one-way
**Use case:** See what would change without actually syncing.
```bash
bm cloud bisync --name research --dry-run
bm project bisync --name research --dry-run
```
**What happens:**
@@ -440,20 +427,20 @@ bm project add work --cloud --local-path ~/work-notes
bm project add personal --cloud --local-path ~/personal
# Establish baselines
bm cloud bisync --name research --resync
bm cloud bisync --name work --resync
bm cloud bisync --name personal --resync
bm project bisync --name research --resync
bm project bisync --name work --resync
bm project bisync --name personal --resync
# Daily workflow: sync everything
bm cloud bisync --name research
bm cloud bisync --name work
bm cloud bisync --name personal
bm project bisync --name research
bm project bisync --name work
bm project bisync --name personal
```
**Future:** `--all` flag will sync all configured projects:
```bash
bm cloud bisync --all # Coming soon
bm project bisync --all # Coming soon
```
### Mixed Usage
@@ -470,8 +457,8 @@ bm project add archive --cloud
bm project add temp-notes --cloud
# Sync only the configured ones
bm cloud bisync --name research
bm cloud bisync --name work
bm project bisync --name research
bm project bisync --name work
# Archive and temp-notes stay cloud-only
```
@@ -498,9 +485,6 @@ bm cloud create-key "my-laptop" # Creates key and saves it locally
```
The API key is account-level — it grants access to all your cloud projects. It's stored in `~/.basic-memory/config.json` as `cloud_api_key`.
On POSIX systems, Basic Memory writes `~/.basic-memory/` as user-private (`0700`) and
`config.json` as user-read/write only (`0600`). Treat this config file as a credential
file when an API key is saved.
### Setting Project Modes
@@ -590,62 +574,33 @@ bm cloud logout
**Default patterns:**
```gitignore
# Hidden files and directories
.*
# Basic Memory internals
*.db
*.db-shm
*.db-wal
config.json
# Version control
.git
.svn
.git/**
# Python
__pycache__
__pycache__/**
*.pyc
*.pyo
*.pyd
.pytest_cache
.coverage
*.egg-info
.tox
.mypy_cache
.ruff_cache
# Virtual environments
.venv
venv
env
.env
.venv/**
venv/**
# Node.js
node_modules
node_modules/**
# Build artifacts
build
dist
.cache
# IDE
.idea
.vscode
# Basic Memory internals
memory.db/**
memory.db-shm/**
memory.db-wal/**
config.json/**
watch-status.json/**
.bmignore.rclone/**
# OS files
.DS_Store
Thumbs.db
desktop.ini
.DS_Store/**
Thumbs.db/**
# Obsidian
.obsidian
# Temporary files
*.tmp
*.swp
*.swo
*~
# Environment files
.env/**
.env.local/**
```
**How it works:**
@@ -654,11 +609,6 @@ desktop.ini
3. Rclone uses filters during sync
4. Same patterns used by all projects
During conversion, file patterns exclude the direct match and recursive contents.
For example, `config.json` becomes both `- config.json` and `- config.json/**`,
while `.*` becomes both `- .*` and `- .*/**`. Directory-only patterns keep
their trailing slash, so `cache/` becomes `- cache/` and `- cache/**`.
**Customizing:**
```bash
@@ -666,41 +616,14 @@ their trailing slash, so `cache/` becomes `- cache/` and `- cache/**`.
code ~/.basic-memory/.bmignore
# Add custom patterns
echo "*.tmp" >> ~/.basic-memory/.bmignore
echo "*.tmp/**" >> ~/.basic-memory/.bmignore
# Next sync uses updated patterns
bm cloud bisync --name research
bm project bisync --name research
```
## Troubleshooting
### Rclone Setup Cannot Install Automatically
**Problem:** `bm cloud setup` cannot find a supported package manager, or package-manager
installation fails.
**Explanation:** The CLI avoids remote privileged install scripts. It only invokes known
package managers and otherwise asks you to install rclone manually.
**Solution:** Install rclone with your OS package manager, then rerun setup:
```bash
# macOS
brew install rclone
# Debian/Ubuntu
sudo apt install rclone
# Fedora
sudo dnf install rclone
# Arch
sudo pacman -S rclone
# After rclone is on PATH
bm cloud setup
```
### Authentication Issues
**Problem:** "Authentication failed" or "Invalid token"
@@ -732,7 +655,7 @@ bm cloud login
**Solution:**
```bash
bm cloud bisync --name research --resync
bm project bisync --name research --resync
```
**What this does:**
@@ -755,7 +678,7 @@ bm cloud bisync --name research --resync
echo "# Research Notes" > ~/Documents/research/README.md
# Now run bisync
bm cloud bisync --name research --resync
bm project bisync --name research --resync
```
**Why this happens:** Bisync creates listing files that track the state of each side. When both directories are completely empty, these listing files are considered invalid by rclone.
@@ -772,10 +695,10 @@ bm cloud bisync --name research --resync
```bash
# Clear bisync state
bm cloud bisync-reset research
bm project bisync-reset research
# Re-establish baseline
bm cloud bisync --name research --resync
bm project bisync --name research --resync
```
**What this does:**
@@ -795,16 +718,16 @@ bm cloud bisync --name research --resync
```bash
# Check what would be deleted
bm cloud bisync --name research --dry-run
bm project bisync --name research --dry-run
# If correct, establish new baseline
bm cloud bisync --name research --resync
bm project bisync --name research --resync
```
**Solution 2:** Use one-way sync if you know local is correct:
```bash
bm cloud sync --name research
bm project sync --name research
```
### Project Not Configured for Sync
@@ -816,8 +739,8 @@ bm cloud sync --name research
**Solution:**
```bash
bm cloud sync-setup research ~/Documents/research
bm cloud bisync --name research --resync
bm project sync-setup research ~/Documents/research
bm project bisync --name research --resync
```
### Connection Issues
@@ -836,10 +759,8 @@ If instance is down, wait a few minutes and retry.
- **Authentication**: OAuth 2.1 with PKCE flow
- **Tokens**: Stored securely in `~/.basic-memory/basic-memory-cloud.json`
- **API keys**: Stored in `~/.basic-memory/config.json`, which is written with private file permissions on POSIX systems
- **Transport**: All data encrypted in transit (HTTPS)
- **Credentials**: Scoped S3 credentials (read-write to your tenant only)
- **Rclone setup**: Uses package managers or manual instructions; no remote privileged install-script fallback
- **Isolation**: Your data isolated from other tenants
- **Ignore patterns**: Sensitive files automatically excluded via `.bmignore`
@@ -864,7 +785,7 @@ bm cloud create-key <name> # Create API key via cloud API (requires OAuth login
### Setup
```bash
bm cloud setup # Install rclone via package manager and configure credentials
bm cloud setup # Install rclone and configure credentials
```
### Project Management
@@ -874,7 +795,7 @@ bm project list --local # Local project list
bm project list --cloud # Cloud project list
bm project add <name> --cloud # Create cloud project (no sync)
bm project add <name> --cloud --local-path <path> # Create with local sync
bm cloud sync-setup <name> <path> # Add sync to existing project
bm project sync-setup <name> <path> # Add sync to existing project
bm project rm <name> # Delete project
```
@@ -889,19 +810,19 @@ bm project set-local <name> # Revert project to local mode
```bash
# One-way sync (local → cloud)
bm cloud sync --name <project>
bm cloud sync --name <project> --dry-run
bm cloud sync --name <project> --verbose
bm project sync --name <project>
bm project sync --name <project> --dry-run
bm project sync --name <project> --verbose
# Two-way sync (local ↔ cloud) - Recommended
bm cloud bisync --name <project> # After first --resync
bm cloud bisync --name <project> --resync # First time / force baseline
bm cloud bisync --name <project> --dry-run
bm cloud bisync --name <project> --verbose
bm project bisync --name <project> # After first --resync
bm project bisync --name <project> --resync # First time / force baseline
bm project bisync --name <project> --dry-run
bm project bisync --name <project> --verbose
# Integrity check
bm cloud check --name <project>
bm cloud check --name <project> --one-way
bm project check --name <project>
bm project check --name <project> --one-way
# List project files by route
bm project ls --name <project> # Default target: local
@@ -917,9 +838,9 @@ bm project ls --name <project> --cloud --path <subpath>
1. **Authenticate cloud access** - `bm cloud login`
2. **Install rclone** - `bm cloud setup`
3. **Add projects with sync** - `bm project add research --cloud --local-path ~/Documents/research`
4. **Preview first sync** - `bm cloud bisync --name research --resync --dry-run`
5. **Establish baseline** - `bm cloud bisync --name research --resync`
6. **Daily workflow** - `bm cloud bisync --name research`
4. **Preview first sync** - `bm project bisync --name research --resync --dry-run`
5. **Establish baseline** - `bm project bisync --name research --resync`
6. **Daily workflow** - `bm project bisync --name research`
**Key benefits:**
- ✅ Each project independently syncs (or doesn't)
-1
View File
@@ -263,7 +263,6 @@ The sqlite-vec extension is loaded per-connection. Vector tables are created laz
### Postgres (cloud)
- **Vector storage**: [pgvector](https://github.com/pgvector/pgvector) with HNSW indexing
- **Local Docker**: use `docker-compose-postgres.yml` (`pgvector/pgvector:pg17`). Plain `postgres:17` lacks the extension; run `CREATE EXTENSION IF NOT EXISTS vector;` on any external instance before first migration.
- **Chunk metadata table**: Created via Alembic migration (`search_vector_chunks` with `BIGSERIAL` primary key)
- **Embedding table**: `search_vector_embeddings` created at runtime (dimension-dependent, same pattern as SQLite)
- **Index**: HNSW index on the embedding column for fast approximate nearest-neighbour queries
+2 -4
View File
@@ -25,12 +25,11 @@ dependencies = [
"unidecode>=1.3.8",
"dateparser>=1.2.0",
"watchfiles>=1.0.4",
"fastapi[standard]>=0.136.1",
"fastapi[standard]>=0.115.8",
"alembic>=1.14.1",
"pillow>=11.1.0",
"pybars3>=0.9.7",
# Keep FastMCP pinned until each minor upgrade passes the MCP transport matrix.
"fastmcp==3.3.1",
"fastmcp>=3.0.1,<4",
"pyjwt>=2.10.1",
"python-dotenv>=1.1.0",
"pytest-aio>=1.9.0",
@@ -49,7 +48,6 @@ dependencies = [
"sqlite-vec>=0.1.6",
"openai>=1.100.2",
"logfire>=4.19.0",
"psutil>=5.9.0",
]
[project.urls]
+2 -2
View File
@@ -6,12 +6,12 @@
"url": "https://github.com/basicmachines-co/basic-memory.git",
"source": "github"
},
"version": "0.21.5",
"version": "0.20.3",
"packages": [
{
"registryType": "pypi",
"identifier": "basic-memory",
"version": "0.21.5",
"version": "0.20.3",
"runtimeHint": "uvx",
"runtimeArguments": [
{"type": "positional", "value": "basic-memory"},
+1 -1
View File
@@ -1,7 +1,7 @@
"""basic-memory - Local-first knowledge management combining Zettelkasten with knowledge graphs"""
# Package version - updated by release automation
__version__ = "0.21.5"
__version__ = "0.20.3"
# API version for FastAPI - independent of package version
__api_version__ = "v0"
@@ -1,86 +0,0 @@
"""Remove orphaned search rows whose project was already deleted.
Revision ID: n7i8j9k0l1m2
Revises: m6h7i8j9k0l1
Create Date: 2026-05-15 18:30:00.000000
"""
from typing import Sequence, Union
from alembic import op
from sqlalchemy import inspect
revision: str = "n7i8j9k0l1m2"
down_revision: Union[str, None] = "m6h7i8j9k0l1"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def _table_exists(connection, table_name: str) -> bool:
"""Inspector-based table check, dialect agnostic.
Trigger: SQLite creates search_index as an FTS5 virtual table at runtime
via SearchRepository.init_search_index, not through Alembic, so fresh
installs hit this migration before the table exists.
Why: a blind DELETE against a missing table fails the whole upgrade.
Outcome: callers skip the sweep when the table isn't present yet — the
runtime-created table on a fresh DB has no orphans to clean.
"""
return table_name in inspect(connection).get_table_names()
def upgrade() -> None:
"""Purge orphaned search rows left over from prior project deletions.
Trigger: project deletion on SQLite never removed the derived FTS rows,
because the FTS5 virtual table can't carry a foreign key. The leak shows
up in two shapes:
1. project_id no longer exists in `project` (deleted project, id never
reused).
2. project_id still exists but `entity_id` no longer exists in `entity`
— auto-increment handed the id to a brand-new project and the FTS
rows from the deleted predecessor masquerade as the new tenant's data.
Why: search_index.project_id is the only scope predicate the search
repository applies, so leftover rows surface under the wrong project on
every search.
Outcome: a one-time sweep deletes both shapes, from the FTS index and
from search_vector_chunks. Postgres already cascaded on FK delete, so
these statements are no-ops there.
"""
connection = op.get_bind()
if _table_exists(connection, "search_index"):
op.execute(
"""
DELETE FROM search_index
WHERE project_id NOT IN (SELECT id FROM project)
"""
)
op.execute(
"""
DELETE FROM search_index
WHERE entity_id IS NOT NULL
AND entity_id NOT IN (SELECT id FROM entity)
"""
)
if _table_exists(connection, "search_vector_chunks"):
op.execute(
"""
DELETE FROM search_vector_chunks
WHERE project_id NOT IN (SELECT id FROM project)
"""
)
op.execute(
"""
DELETE FROM search_vector_chunks
WHERE entity_id NOT IN (SELECT id FROM entity)
"""
)
def downgrade() -> None:
"""No-op: orphan rows cannot be reconstructed."""
pass
+1 -37
View File
@@ -4,7 +4,6 @@ from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, Request
from fastapi.exception_handlers import http_exception_handler
from fastapi.responses import JSONResponse
from fastapi.routing import APIRouter
from loguru import logger
@@ -30,12 +29,6 @@ import logfire
from basic_memory.config import init_api_logging
from basic_memory.services.exceptions import EntityAlreadyExistsError
from basic_memory.services.initialization import initialize_app
from basic_memory.workspace_context import (
WORKSPACE_SLUG_HEADER,
WORKSPACE_TYPE_HEADER,
workspace_permalink_context_validation_error,
workspace_permalink_context,
)
@asynccontextmanager
@@ -94,32 +87,6 @@ app = FastAPI(
lifespan=lifespan,
)
@app.middleware("http")
async def workspace_permalink_context_middleware(request: Request, call_next):
"""Populate workspace permalink context from request headers."""
workspace_slug = request.headers.get(WORKSPACE_SLUG_HEADER)
workspace_type = request.headers.get(WORKSPACE_TYPE_HEADER)
validation_error = workspace_permalink_context_validation_error(workspace_slug, workspace_type)
if validation_error is not None:
return JSONResponse(
status_code=400,
content={"detail": validation_error},
)
if not workspace_slug:
return await call_next(request)
# ContextVar state remains active across the awaited downstream handler while
# this context manager is open, so entity creation can see request metadata.
with workspace_permalink_context(
workspace_slug=workspace_slug,
workspace_type=workspace_type,
):
return await call_next(request)
# Include v2 routers FIRST (more specific paths must match before /{project} catch-all)
app.include_router(v2_knowledge, prefix="/v2/projects/{project_id}")
app.include_router(v2_memory, prefix="/v2/projects/{project_id}")
@@ -179,7 +146,4 @@ async def exception_handler(request, exc): # pragma: no cover
error_type=type(exc).__name__,
error=str(exc),
)
return await http_exception_handler(
request,
HTTPException(status_code=500, detail="Internal server error"),
)
return await http_exception_handler(request, HTTPException(status_code=500, detail=str(exc)))
@@ -10,7 +10,6 @@ import logging
from fastapi import APIRouter, Form, HTTPException, UploadFile, status, Path
from basic_memory.deps import (
AppConfigDep,
ChatGPTImporterV2ExternalDep,
ClaudeConversationsImporterV2ExternalDep,
ClaudeProjectsImporterV2ExternalDep,
@@ -28,21 +27,9 @@ logger = logging.getLogger(__name__)
router = APIRouter(prefix="/import", tags=["import-v2"])
async def read_import_upload(file: UploadFile, max_bytes: int) -> bytes:
"""Read an import upload with a hard cap before JSON parsing."""
content = await file.read(max_bytes + 1)
if len(content) > max_bytes:
raise HTTPException(
status_code=status.HTTP_413_CONTENT_TOO_LARGE,
detail=f"Import file exceeds maximum size of {max_bytes} bytes.",
)
return content
@router.post("/chatgpt", response_model=ChatImportResult)
async def import_chatgpt(
importer: ChatGPTImporterV2ExternalDep,
config: AppConfigDep,
file: UploadFile,
project_id: str = Path(..., description="Project external UUID"),
directory: str = Form("conversations"),
@@ -62,13 +49,12 @@ async def import_chatgpt(
HTTPException: If import fails.
"""
logger.info(f"V2 Importing ChatGPT conversations for project {project_id}")
return await import_file(importer, file, directory, config.import_upload_max_bytes)
return await import_file(importer, file, directory)
@router.post("/claude/conversations", response_model=ChatImportResult)
async def import_claude_conversations(
importer: ClaudeConversationsImporterV2ExternalDep,
config: AppConfigDep,
file: UploadFile,
project_id: str = Path(..., description="Project external UUID"),
directory: str = Form("conversations"),
@@ -88,13 +74,12 @@ async def import_claude_conversations(
HTTPException: If import fails.
"""
logger.info(f"V2 Importing Claude conversations for project {project_id}")
return await import_file(importer, file, directory, config.import_upload_max_bytes)
return await import_file(importer, file, directory)
@router.post("/claude/projects", response_model=ProjectImportResult)
async def import_claude_projects(
importer: ClaudeProjectsImporterV2ExternalDep,
config: AppConfigDep,
file: UploadFile,
project_id: str = Path(..., description="Project external UUID"),
directory: str = Form("projects"),
@@ -114,13 +99,12 @@ async def import_claude_projects(
HTTPException: If import fails.
"""
logger.info(f"V2 Importing Claude projects for project {project_id}")
return await import_file(importer, file, directory, config.import_upload_max_bytes)
return await import_file(importer, file, directory)
@router.post("/memory-json", response_model=EntityImportResult)
async def import_memory_json(
importer: MemoryJsonImporterV2ExternalDep,
config: AppConfigDep,
file: UploadFile,
project_id: str = Path(..., description="Project external UUID"),
directory: str = Form("conversations"),
@@ -142,7 +126,7 @@ async def import_memory_json(
logger.info(f"V2 Importing memory.json for project {project_id}")
try:
file_data = []
file_bytes = await read_import_upload(file, config.import_upload_max_bytes)
file_bytes = await file.read()
file_str = file_bytes.decode("utf-8")
for line in file_str.splitlines():
json_data = json.loads(line)
@@ -154,8 +138,6 @@ async def import_memory_json(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=result.error_message or "Import failed",
)
except HTTPException:
raise
except Exception as e:
logger.exception("V2 Import failed")
raise HTTPException(
@@ -165,16 +147,13 @@ async def import_memory_json(
return result
async def import_file(
importer: Importer, file: UploadFile, destination_directory: str, max_bytes: int
):
async def import_file(importer: Importer, file: UploadFile, destination_directory: str):
"""Helper function to import a file using an importer instance.
Args:
importer: The importer instance to use
file: The file to import
destination_directory: Destination directory for imported content
max_bytes: Maximum upload size in bytes; raises HTTP 413 if exceeded
Returns:
Import result from the importer
@@ -184,8 +163,7 @@ async def import_file(
"""
try:
# Process file
upload_bytes = await read_import_upload(file, max_bytes)
json_data = json.loads(upload_bytes)
json_data = json.load(file.file)
result = await importer.import_data(json_data, destination_directory)
if not result.success: # pragma: no cover
raise HTTPException(
@@ -195,8 +173,6 @@ async def import_file(
return result
except HTTPException:
raise
except Exception as e:
logger.exception("V2 Import failed")
raise HTTPException(
@@ -119,7 +119,12 @@ async def get_orphan_entities(
project_id: ProjectExternalIdPathDep,
entity_repository: EntityRepositoryV2ExternalDep,
) -> OrphanEntitiesResponse:
"""Return entities that have no incoming or outgoing relations."""
"""Return entities that have no relations in the knowledge graph.
Orphan entities have no incoming or outgoing connections — they are isolated
nodes that may indicate newly created notes not yet linked to the graph,
or entities whose relations have been removed.
"""
with logfire.span(
"api.request.knowledge.get_orphans",
entrypoint="api",
@@ -11,7 +11,7 @@ Key improvements:
"""
import os
from typing import Literal, Optional
from typing import Optional
from fastapi import APIRouter, HTTPException, Body, Query, Path
from loguru import logger
@@ -25,8 +25,6 @@ from basic_memory.deps import (
ProjectExternalIdPathDep,
)
from basic_memory.schemas import SyncReportResponse
from basic_memory.models import Project
from basic_memory.repository.project_repository import ProjectRepository
from basic_memory.schemas.project_info import (
ProjectItem,
ProjectList,
@@ -38,71 +36,6 @@ from basic_memory.schemas.v2 import ProjectResolveRequest, ProjectResolveRespons
from basic_memory.utils import normalize_project_path, generate_permalink
router = APIRouter(prefix="/projects", tags=["project_management-v2"])
ProjectResolveMethod = Literal["external_id", "name", "permalink"]
def _split_qualified_project_identifier(identifier: str) -> tuple[str | None, str]:
"""Split ``<workspace>/<project>`` identifiers while preserving plain project names."""
cleaned = identifier.strip()
if "/" not in cleaned:
return None, cleaned
workspace_identifier, project_identifier = cleaned.split("/", 1)
if not workspace_identifier or not project_identifier:
return None, cleaned
return workspace_identifier, project_identifier
async def _resolve_project_identifier_candidate(
project_repository: ProjectRepository,
identifier: str,
) -> tuple[Project | None, ProjectResolveMethod]:
"""Resolve one project identifier candidate and report the matching method."""
identifier_permalink = generate_permalink(identifier)
project = await project_repository.get_by_external_id(identifier)
if project:
return project, "external_id"
project = await project_repository.get_by_permalink(identifier_permalink)
if project:
return project, "permalink"
project = await project_repository.get_by_name_case_insensitive(identifier)
if project:
return project, "name" # pragma: no cover
return None, "name"
async def _resolve_project_identifier(
project_repository: ProjectRepository,
identifier: str,
) -> tuple[Project | None, ProjectResolveMethod]:
"""Resolve exact identifiers first, then accepted workspace-qualified forms."""
project, resolution_method = await _resolve_project_identifier_candidate(
project_repository,
identifier,
)
if project:
return project, resolution_method
workspace_identifier, project_identifier = _split_qualified_project_identifier(identifier)
if workspace_identifier is None:
return None, resolution_method
# Trigger: an MCP disambiguation error suggested ``workspace/project``.
# Why: request routing already selected the workspace/tenant; this endpoint
# only needs the project segment to validate the active project.
# Outcome: models can follow the hint verbatim instead of looping on a 404.
project, resolution_method = await _resolve_project_identifier_candidate(
project_repository,
project_identifier,
)
if project:
return project, resolution_method
return None, resolution_method
@router.get("/", response_model=ProjectList)
@@ -314,10 +247,28 @@ async def resolve_project_identifier(
"""
logger.info(f"API v2 request: resolve_project_identifier for '{data.identifier}'")
project, resolution_method = await _resolve_project_identifier(
project_repository,
data.identifier,
)
# Generate permalink for comparison
identifier_permalink = generate_permalink(data.identifier)
resolution_method = "name"
project = None
# Try external_id first (UUID format)
project = await project_repository.get_by_external_id(data.identifier)
if project:
resolution_method = "external_id"
# If not found by external_id, try by permalink (exact match)
if not project:
project = await project_repository.get_by_permalink(identifier_permalink)
if project:
resolution_method = "permalink"
# If not found by permalink, try case-insensitive name search
if not project:
project = await project_repository.get_by_name_case_insensitive(data.identifier)
if project:
resolution_method = "name" # pragma: no cover
if not project:
raise HTTPException(status_code=404, detail=f"Project not found: '{data.identifier}'")
@@ -4,8 +4,6 @@ This router uses external_id UUIDs for stable, API-friendly routing.
V1 uses string-based project names which are less efficient and less stable.
"""
import asyncio
from fastapi import APIRouter, HTTPException, Path
import logfire
@@ -14,7 +12,7 @@ from basic_memory.repository.semantic_errors import (
SemanticDependenciesMissingError,
SemanticSearchDisabledError,
)
from basic_memory.schemas.search import SearchQuery, SearchResponse, SearchRetrievalMode
from basic_memory.schemas.search import SearchQuery, SearchResponse
from basic_memory.deps import (
SearchServiceV2ExternalDep,
EntityServiceV2ExternalDep,
@@ -67,7 +65,7 @@ async def search(
has_filters=bool(query.note_types or query.entity_types or query.metadata_filters),
):
offset = (page - 1) * page_size
exact_count_available = query.retrieval_mode == SearchRetrievalMode.FTS
fetch_limit = page_size + 1
try:
with logfire.span(
"api.search.search.execute_query",
@@ -77,14 +75,7 @@ async def search(
page=page,
page_size=page_size,
):
if exact_count_available:
results, total = await asyncio.gather(
search_service.search(query, limit=page_size, offset=offset),
search_service.count(query),
)
else:
results = await search_service.search(query, limit=page_size + 1, offset=offset)
total = 0
results = await search_service.search(query, limit=fetch_limit, offset=offset)
except SemanticSearchDisabledError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except SemanticDependenciesMissingError as exc:
@@ -99,15 +90,9 @@ async def search(
phase="paginate_results",
result_count=len(results),
):
if exact_count_available:
has_more = offset + len(results) < total
else:
# Trigger: semantic modes would need another vector/hybrid retrieval to count.
# Why: search requests should not pay for a second semantic pass.
# Outcome: preserve probe pagination for semantic search and leave total at 0.
has_more = len(results) > page_size
if has_more:
results = results[:page_size]
has_more = len(results) > page_size
if has_more:
results = results[:page_size]
with logfire.span(
"api.search.search.hydrate_results",
@@ -128,7 +113,6 @@ async def search(
results=search_results,
current_page=page,
page_size=page_size,
total=total,
has_more=has_more,
)
+3 -5
View File
@@ -18,7 +18,7 @@ from basic_memory.services.context_service import (
class EntityBatchLookup(Protocol):
async def find_by_ids_for_hydration(self, ids: List[int]) -> Sequence[Any]: ...
async def find_by_ids(self, ids: List[int]) -> Sequence[Any]: ...
class EntityServiceBatchLookup(Protocol):
@@ -76,7 +76,7 @@ async def to_graph_context(
if item.to_id:
entity_ids_needed.add(item.to_id)
# Batch fetch just the entity fields needed to shape the response.
# Batch fetch all entities at once - get both title and external_id
entity_title_lookup: dict[int, str] = {}
entity_external_id_lookup: dict[int, str] = {}
if entity_ids_needed:
@@ -87,9 +87,7 @@ async def to_graph_context(
phase="lookup_entities",
result_count=len(entity_ids_needed),
):
entities = await entity_repository.find_by_ids_for_hydration(
list(entity_ids_needed)
)
entities = await entity_repository.find_by_ids(list(entity_ids_needed))
for e in entities:
entity_title_lookup[e.id] = e.title
entity_external_id_lookup[e.id] = e.external_id
+3 -2
View File
@@ -1,9 +1,10 @@
"""CLI commands for basic-memory."""
from . import status, db, doctor, import_memory_json, mcp, import_claude_conversations, orphans
from . import status, db, doctor, import_memory_json, mcp, import_claude_conversations
from . import (
import_claude_projects,
import_chatgpt,
orphans,
tool,
project,
format,
@@ -18,9 +19,9 @@ __all__ = [
"import_memory_json",
"mcp",
"import_claude_conversations",
"orphans",
"import_claude_projects",
"import_chatgpt",
"orphans",
"tool",
"project",
"format",
@@ -14,24 +14,6 @@ class BisyncError(Exception):
pass
def _rclone_exclude_filters(pattern: str) -> list[str]:
"""Return rclone exclude filters for a gitignore-style pattern."""
if pattern.endswith("/"):
# Trigger: gitignore-style patterns ending in / are directory-only rules.
# Why: stripping the slash would also exclude a same-named file.
# Outcome: rclone keeps the directory rule and excludes recursive contents.
return [f"- {pattern}", f"- {pattern}**"]
path_pattern = pattern.removesuffix("/**")
# Trigger: rclone treats a directory contents filter separately from the
# directory/file path itself.
# Why: files like config.json and directory markers like .obsidian must both
# be excluded, along with anything below matching directories.
# Outcome: every ignore pattern excludes the direct match and recursive children.
return [f"- {path_pattern}", f"- {path_pattern}/**"]
async def get_mount_info() -> TenantMountInfo:
"""Get current tenant information from cloud API."""
try:
@@ -96,11 +78,19 @@ def convert_bmignore_to_rclone_filters() -> Path:
patterns.append(line)
continue
patterns.extend(_rclone_exclude_filters(line))
# Convert gitignore pattern to rclone filter syntax
# gitignore: node_modules → rclone: - node_modules/**
# gitignore: *.pyc → rclone: - *.pyc
if "*" in line:
# Pattern already has wildcard, just add exclude prefix
patterns.append(f"- {line}")
else:
# Directory pattern - add /** for recursive exclude
patterns.append(f"- {line}/**")
except Exception:
# If we can't read the file, create a minimal filter
patterns = ["# Error reading .bmignore, using minimal filters", "- .git", "- .git/**"]
patterns = ["# Error reading .bmignore, using minimal filters", "- .git/**"]
# Write rclone filter file
rclone_filter_path.write_text("\n".join(patterns) + "\n")
@@ -76,22 +76,10 @@ def login():
@cloud_app.command()
def logout():
"""Remove stored OAuth tokens and clear cached workspace selection."""
config_manager = ConfigManager()
config = config_manager.config
"""Remove stored OAuth tokens."""
config = ConfigManager().config
auth = CLIAuth(client_id=config.cloud_client_id, authkit_domain=config.cloud_domain)
auth.logout()
# Trigger: ending a session must invalidate the cached workspace.
# Why: a follow-up `bm cloud login` (often as a different user, or returning
# from an org workspace to personal) inherits the previous selection
# and silently routes everything through the wrong tenant. See #755.
# Outcome: re-login starts from a clean slate; the user picks again via
# `bm cloud workspace set-default` or per-project --workspace.
if config.default_workspace is not None:
config.default_workspace = None
config_manager.save_config(config)
console.print("[dim]API key (if configured) remains available for cloud project routing.[/dim]")
@@ -179,7 +167,7 @@ def setup() -> None:
console.print("1. Add a project with local sync path:")
console.print(" bm project add research --cloud --local-path ~/Documents/research")
console.print("\n Or configure sync for an existing project:")
console.print(" bm cloud sync-setup research ~/Documents/research")
console.print(" bm project sync-setup research ~/Documents/research")
console.print("\n2. Preview the initial sync (recommended):")
console.print(" bm project bisync --name research --resync --dry-run")
console.print("\n3. If all looks good, run the actual sync:")
@@ -95,10 +95,7 @@ def sync_project_command(
dry_run: bool = typer.Option(False, "--dry-run", help="Preview changes without syncing"),
verbose: bool = typer.Option(False, "--verbose", "-v", help="Show detailed output"),
) -> None:
"""Personal workspace local mirror only.
One-way sync: local -> cloud (make cloud identical to local).
Not supported for Team workspaces - use cloud API/MCP routing instead.
"""One-way sync: local -> cloud (make cloud identical to local).
Example:
bm cloud sync --name research
@@ -146,10 +143,7 @@ def bisync_project_command(
resync: bool = typer.Option(False, "--resync", help="Force new baseline"),
verbose: bool = typer.Option(False, "--verbose", "-v", help="Show detailed output"),
) -> None:
"""Personal workspace local mirror only.
Two-way sync: local <-> cloud (bidirectional sync).
Not supported for Team workspaces - use cloud API/MCP routing instead.
"""Two-way sync: local <-> cloud (bidirectional sync).
Examples:
bm cloud bisync --name research --resync # First time
@@ -209,10 +203,7 @@ def check_project_command(
name: str = typer.Option(..., "--name", help="Project name to check"),
one_way: bool = typer.Option(False, "--one-way", help="Check one direction only (faster)"),
) -> None:
"""Personal workspace local mirror only.
Verify file integrity between local and cloud.
Not supported for Team workspaces - use cloud API/MCP routing instead.
"""Verify file integrity between local and cloud.
Example:
bm cloud check --name research
@@ -255,10 +246,7 @@ def check_project_command(
def bisync_reset(
name: str = typer.Argument(..., help="Project name to reset bisync state for"),
) -> None:
"""Personal workspace local mirror only.
Clear bisync state for a project.
Not supported for Team workspaces - use cloud API/MCP routing instead.
"""Clear bisync state for a project.
This removes the bisync metadata files, forcing a fresh --resync on next bisync.
Useful when bisync gets into an inconsistent state or when remote path changes.
@@ -289,10 +277,7 @@ def setup_project_sync(
name: str = typer.Argument(..., help="Project name"),
local_path: str = typer.Argument(..., help="Local sync directory"),
) -> None:
"""Personal workspace local mirror only.
Configure local sync for an existing cloud project.
Not supported for Team workspaces - use cloud API/MCP routing instead.
"""Configure local sync for an existing cloud project.
Example:
bm cloud sync-setup research ~/Documents/research
@@ -4,7 +4,7 @@ import os
import platform
import shutil
import subprocess
from typing import Any, Optional, cast
from typing import Optional
from rich.console import Console
@@ -53,9 +53,7 @@ def run_command(command: list[str], check: bool = True) -> subprocess.CompletedP
def install_rclone_macos() -> None:
"""Install rclone on macOS using package managers."""
install_errors: list[str] = []
"""Install rclone on macOS using Homebrew or official script."""
# Try Homebrew first
if shutil.which("brew"):
try:
@@ -63,37 +61,35 @@ def install_rclone_macos() -> None:
run_command(["brew", "install", "rclone"])
console.print("[green]rclone installed via Homebrew[/green]")
return
except RcloneInstallError as exc:
install_errors.append(f"Homebrew failed: {exc}")
console.print("[yellow]Homebrew installation failed, trying MacPorts...[/yellow]")
except RcloneInstallError:
console.print(
"[yellow]Homebrew installation failed, trying official script...[/yellow]"
)
if shutil.which("port"):
try:
console.print("[blue]Installing rclone via MacPorts...[/blue]")
run_command(["sudo", "port", "install", "rclone"])
console.print("[green]rclone installed via MacPorts[/green]")
return
except RcloneInstallError as exc:
install_errors.append(f"MacPorts failed: {exc}")
console.print("[yellow]MacPorts installation failed[/yellow]")
details = "\n".join(f"- {error}" for error in install_errors)
if details:
details = f"\n\nAttempts:\n{details}"
raise RcloneInstallError(
"Could not install rclone automatically with an available package manager.\n\n"
"Install rclone manually with one of:\n"
" brew install rclone\n"
" sudo port install rclone\n"
" Download from https://rclone.org/downloads/ and add rclone to PATH"
f"{details}"
)
# Fallback to official script
console.print("[blue]Installing rclone via official script...[/blue]")
try:
run_command(["sh", "-c", "curl https://rclone.org/install.sh | sudo bash"])
console.print("[green]rclone installed via official script[/green]")
except RcloneInstallError:
raise RcloneInstallError(
"Failed to install rclone. Please install manually: brew install rclone"
)
def install_rclone_linux() -> None:
"""Install rclone on Linux using package managers."""
install_errors: list[str] = []
"""Install rclone on Linux using package managers or official script."""
# Try snap first (most universal)
if shutil.which("snap"):
try:
console.print("[blue]Installing rclone via snap...[/blue]")
run_command(["sudo", "snap", "install", "rclone"])
console.print("[green]rclone installed via snap[/green]")
return
except RcloneInstallError:
console.print("[yellow]Snap installation failed, trying apt...[/yellow]")
# Try apt (Debian/Ubuntu)
if shutil.which("apt"):
try:
console.print("[blue]Installing rclone via apt...[/blue]")
@@ -101,75 +97,18 @@ def install_rclone_linux() -> None:
run_command(["sudo", "apt", "install", "-y", "rclone"])
console.print("[green]rclone installed via apt[/green]")
return
except RcloneInstallError as exc:
install_errors.append(f"apt failed: {exc}")
console.print("[yellow]apt installation failed, trying dnf...[/yellow]")
except RcloneInstallError:
console.print("[yellow]apt installation failed, trying official script...[/yellow]")
if shutil.which("dnf"):
try:
console.print("[blue]Installing rclone via dnf...[/blue]")
run_command(["sudo", "dnf", "install", "-y", "rclone"])
console.print("[green]rclone installed via dnf[/green]")
return
except RcloneInstallError as exc:
install_errors.append(f"dnf failed: {exc}")
console.print("[yellow]dnf installation failed, trying yum...[/yellow]")
if shutil.which("yum"):
try:
console.print("[blue]Installing rclone via yum...[/blue]")
run_command(["sudo", "yum", "install", "-y", "rclone"])
console.print("[green]rclone installed via yum[/green]")
return
except RcloneInstallError as exc:
install_errors.append(f"yum failed: {exc}")
console.print("[yellow]yum installation failed, trying pacman...[/yellow]")
if shutil.which("pacman"):
try:
console.print("[blue]Installing rclone via pacman...[/blue]")
run_command(["sudo", "pacman", "-S", "--noconfirm", "rclone"])
console.print("[green]rclone installed via pacman[/green]")
return
except RcloneInstallError as exc:
install_errors.append(f"pacman failed: {exc}")
console.print("[yellow]pacman installation failed, trying zypper...[/yellow]")
if shutil.which("zypper"):
try:
console.print("[blue]Installing rclone via zypper...[/blue]")
run_command(["sudo", "zypper", "--non-interactive", "install", "rclone"])
console.print("[green]rclone installed via zypper[/green]")
return
except RcloneInstallError as exc:
install_errors.append(f"zypper failed: {exc}")
console.print("[yellow]zypper installation failed, trying snap...[/yellow]")
if shutil.which("snap"):
try:
console.print("[blue]Installing rclone via snap...[/blue]")
run_command(["sudo", "snap", "install", "rclone"])
console.print("[green]rclone installed via snap[/green]")
return
except RcloneInstallError as exc:
install_errors.append(f"snap failed: {exc}")
console.print("[yellow]snap installation failed[/yellow]")
details = "\n".join(f"- {error}" for error in install_errors)
if details:
details = f"\n\nAttempts:\n{details}"
raise RcloneInstallError(
"Could not install rclone automatically with an available package manager.\n\n"
"Install rclone manually with one of your OS package managers, for example:\n"
" sudo apt install rclone\n"
" sudo dnf install rclone\n"
" sudo yum install rclone\n"
" sudo pacman -S rclone\n"
" sudo zypper install rclone\n"
" sudo snap install rclone\n"
"Or download from https://rclone.org/downloads/ and add rclone to PATH"
f"{details}"
)
# Fallback to official script
console.print("[blue]Installing rclone via official script...[/blue]")
try:
run_command(["sh", "-c", "curl https://rclone.org/install.sh | sudo bash"])
console.print("[green]rclone installed via official script[/green]")
except RcloneInstallError:
raise RcloneInstallError(
"Failed to install rclone. Please install manually: sudo snap install rclone"
)
def install_rclone_windows() -> None:
@@ -270,38 +209,27 @@ def refresh_windows_path() -> None:
if platform.system().lower() != "windows":
return
# Importing here after performing platform detection. Non-Windows type checkers may still
# resolve a stub without registry members, so keep this platform-only module dynamic here.
# Importing here after performing platform detection. Also note that we have to ignore pylance/pyright
# warnings about winreg attributes so that "errors" don't appear on non-Windows platforms.
import winreg
winreg_module = cast(Any, winreg)
user_key_path = r"Environment"
system_key_path = r"System\CurrentControlSet\Control\Session Manager\Environment"
new_path = ""
# Read user PATH
try:
reg_key = winreg_module.OpenKey(
winreg_module.HKEY_CURRENT_USER,
user_key_path,
0,
winreg_module.KEY_READ,
)
user_path, _ = winreg_module.QueryValueEx(reg_key, "PATH")
winreg_module.CloseKey(reg_key)
reg_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, user_key_path, 0, winreg.KEY_READ) # type: ignore[reportAttributeAccessIssue]
user_path, _ = winreg.QueryValueEx(reg_key, "PATH") # type: ignore[reportAttributeAccessIssue]
winreg.CloseKey(reg_key) # type: ignore[reportAttributeAccessIssue]
except Exception:
user_path = ""
# Read system PATH
try:
reg_key = winreg_module.OpenKey(
winreg_module.HKEY_LOCAL_MACHINE,
system_key_path,
0,
winreg_module.KEY_READ,
)
system_path, _ = winreg_module.QueryValueEx(reg_key, "PATH")
winreg_module.CloseKey(reg_key)
reg_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, system_key_path, 0, winreg.KEY_READ) # type: ignore[reportAttributeAccessIssue]
system_path, _ = winreg.QueryValueEx(reg_key, "PATH") # type: ignore[reportAttributeAccessIssue]
winreg.CloseKey(reg_key) # type: ignore[reportAttributeAccessIssue]
except Exception:
system_path = ""
@@ -6,11 +6,10 @@ from rich.table import Table
from basic_memory.cli.commands.command_utils import run_with_cleanup
from basic_memory.config import ConfigManager
from basic_memory.mcp.project_context import get_available_workspaces
from basic_memory.schemas.cloud import (
format_workspace_choices,
format_workspace_selection_choices,
workspace_matches_identifier,
from basic_memory.mcp.project_context import (
_workspace_choices,
_workspace_matches_identifier,
get_available_workspaces,
)
console = Console()
@@ -63,10 +62,7 @@ def list_workspaces() -> None:
@workspace_app.command("set-default")
def set_default_workspace(
identifier: str = typer.Argument(
...,
help="Workspace name, slug, type, or tenant_id to set as default",
),
identifier: str = typer.Argument(..., help="Workspace name or tenant_id to set as default"),
) -> None:
"""Set the default cloud workspace.
@@ -75,7 +71,6 @@ def set_default_workspace(
Examples:
bm cloud workspace set-default Personal
bm cloud workspace set-default organization
bm cloud workspace set-default 11111111-1111-1111-1111-111111111111
"""
@@ -92,19 +87,19 @@ def set_default_workspace(
console.print("[yellow]No accessible workspaces found.[/yellow]")
raise typer.Exit(1)
matches = [ws for ws in workspaces if workspace_matches_identifier(ws, identifier)]
matches = [ws for ws in workspaces if _workspace_matches_identifier(ws, identifier)]
if not matches:
console.print(f"[red]Error: Workspace '{identifier}' not found[/red]")
console.print(f"[dim]Available:\n{format_workspace_choices(workspaces)}[/dim]")
console.print(f"[dim]Available:\n{_workspace_choices(workspaces)}[/dim]")
raise typer.Exit(1)
if len(matches) > 1:
console.print(f"[red]Error: Workspace '{identifier}' matches multiple workspaces.[/red]")
console.print(
"[dim]Choose one of these matching workspaces by slug:\n"
f"{format_workspace_selection_choices(matches)}[/dim]"
f"[red]Error: Workspace name '{identifier}' matches multiple workspaces. "
f"Use tenant_id instead.[/red]"
)
console.print(f"[dim]Available:\n{_workspace_choices(workspaces)}[/dim]")
raise typer.Exit(1)
selected = matches[0]
+1 -118
View File
@@ -1,10 +1,8 @@
"""Database management commands."""
import os
from dataclasses import dataclass
from pathlib import Path, PurePosixPath, PureWindowsPath
from pathlib import Path
import psutil
import typer
from loguru import logger
from rich.console import Console
@@ -23,103 +21,6 @@ from basic_memory.sync.sync_service import get_sync_service
console = Console()
def _is_basic_memory_mcp(cmdline: list[str]) -> bool:
"""Heuristic: does this argv represent a `basic-memory mcp` server?
The MCP server can be launched any of:
basic-memory mcp
bm mcp # entrypoint alias from pyproject.toml
python -m basic_memory.cli.main mcp # module form
uv run basic-memory mcp / uv run bm mcp # uv wrappers
/abs/path/to/{bm,basic-memory}[.exe] mcp
A reliable match needs both signals:
1. "mcp" appears as an exact argv token (not "mcp-foo").
2. Some argv token names the basic-memory entrypoint — either by
hyphen/underscore form, or as a `bm` script (covers `/usr/local/bin/bm`,
`bm.exe`, etc. via Path.stem).
"""
if "mcp" not in cmdline:
return False
for arg in cmdline:
if "basic-memory" in arg or "basic_memory" in arg:
return True
# Try both POSIX and Windows path interpretations so a test on
# macOS still recognizes `C:\\...\\bm.exe`, and a real Windows
# run still recognizes `/usr/local/bin/bm`. Path() alone uses
# the host OS, which gives wrong stems for foreign separators.
if PurePosixPath(arg).stem == "bm" or PureWindowsPath(arg).stem == "bm":
return True
return False
def _find_live_mcp_processes() -> list[tuple[int, str]]:
"""Return (pid, joined_cmdline) for live `basic-memory mcp` processes.
Why this exists (issue #765):
On POSIX, `Path.unlink()` removes the directory entry but the inode
survives as long as any process holds the file open. A `bm reset`
run while Claude Desktop (or another MCP client) is alive will
therefore "succeed" — but the still-running MCP keeps reading the
old, now-invisible memory.db inode and returns phantom rows. On
Windows the OS naturally raises PermissionError on `unlink()`, so
the bug is POSIX-specific. We detect proactively to give the same
error experience on every platform before doing damage.
The current process is excluded so this can be called from inside a
`bm reset` invocation. NoSuchProcess / AccessDenied are swallowed
because process tables race with the scan and we don't want a
transient permission error to mask a real zombie.
"""
me = os.getpid()
matches: list[tuple[int, str]] = []
for proc in psutil.process_iter(["pid", "cmdline"]):
try:
pid = proc.info.get("pid")
if pid is None or pid == me:
continue
cmdline = proc.info.get("cmdline") or []
if not cmdline:
continue
if _is_basic_memory_mcp(cmdline):
matches.append((pid, " ".join(cmdline)))
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
return matches
def _abort_if_mcp_processes_alive() -> None:
"""Refuse `bm reset` while basic-memory MCP processes are still running.
See _find_live_mcp_processes for the underlying POSIX-vs-Windows
rationale. Prints a per-PID list and platform-appropriate cleanup
instructions, then exits non-zero so destructive work never starts.
"""
zombies = _find_live_mcp_processes()
if not zombies:
return
console.print("[red]Refusing to reset:[/red] basic-memory MCP processes are still running.")
console.print(
"[yellow]On macOS/Linux these would keep reading the deleted memory.db inode "
"and return phantom search results (see #765).[/yellow]"
)
for pid, cmd in zombies:
console.print(f" PID {pid}: {cmd}")
console.print("\n[bold]How to clean up:[/bold]")
console.print(" 1. Quit Claude Desktop and any other MCP clients.")
if os.name == "nt":
console.print(
" 2. Verify nothing remains: "
"[green]Get-CimInstance Win32_Process | "
"Where-Object {$_.CommandLine -like '*basic-memory*mcp*'}[/green]"
)
else:
console.print(" 2. Verify nothing remains: [green]pgrep -fa 'basic-memory mcp'[/green]")
console.print(" 3. Re-run [green]bm reset[/green].")
raise typer.Exit(1)
@dataclass(slots=True)
class EmbeddingProgress:
"""Typed CLI progress payload for embedding backfills."""
@@ -185,16 +86,6 @@ async def _reindex_projects(app_config):
@app.command()
def reset(
reindex: bool = typer.Option(False, "--reindex", help="Rebuild db index from filesystem"),
force: bool = typer.Option(
False,
"--force",
help=(
"Skip the pre-flight check that refuses to reset while "
"basic-memory MCP processes are running. Use only in "
"automated workflows where you've already ensured no MCP "
"clients are attached to the database."
),
),
): # pragma: no cover
"""Reset database (drop all tables and recreate)."""
console.print(
@@ -203,14 +94,6 @@ def reset(
"Use [green]bm reset --reindex[/green] to automatically rebuild the index afterward."
)
if typer.confirm("Reset the database index?"):
# Pre-flight: refuse to proceed if MCP processes still hold the DB
# file open. POSIX would silently let us unlink the inode while
# they keep reading it; Windows would error here anyway. See
# _find_live_mcp_processes for the full story. --force is the
# documented escape hatch for scripted/CI runs.
if not force:
_abort_if_mcp_processes_alive()
logger.info("Resetting database...")
config_manager = ConfigManager()
app_config = config_manager.config
+33 -31
View File
@@ -5,7 +5,6 @@ from typing import Annotated, Optional
import typer
from loguru import logger
from mcp.server.fastmcp.exceptions import ToolError
from rich.console import Console
from rich.table import Table
@@ -15,12 +14,11 @@ from basic_memory.config import ConfigManager
from basic_memory.mcp.async_client import get_client
from basic_memory.mcp.clients.knowledge import KnowledgeClient
from basic_memory.mcp.project_context import get_active_project
from basic_memory.schemas.v2.graph import GraphNode
console = Console()
async def run_orphans(project: Optional[str] = None) -> tuple[str, list[GraphNode]]:
async def run_orphans(project: Optional[str] = None) -> tuple[str, list[dict]]:
"""Fetch entities that have no relations in the knowledge graph."""
project = project or ConfigManager().default_project
@@ -47,47 +45,51 @@ def orphans(
Orphan entities have no incoming or outgoing connections. These may indicate
newly created notes not yet linked to other entities, or notes that have had
their relations removed.
Use --json for machine-readable output.
Use --local to force local routing when cloud mode is enabled.
Use --cloud to force cloud routing when cloud mode is disabled.
"""
from basic_memory.cli.commands.command_utils import run_with_cleanup
try:
validate_routing_flags(local, cloud)
if not local and not cloud:
local = True
with force_routing(local=local, cloud=cloud):
project_name, entities = run_with_cleanup(run_orphans(project))
if json_output:
print(json.dumps([entity.model_dump(mode="json") for entity in entities], indent=2))
return
print(json.dumps(entities, indent=2, default=str))
else:
if not entities:
console.print(
f"[green]No orphan entities in project '{project_name}'[/green]"
)
return
if not entities:
console.print(f"[green]No orphan entities in project '{project_name}'[/green]")
return
table = Table(title=f"{project_name}: Entities Without Relations ({len(entities)} total)")
table.add_column("Title", style="cyan")
table.add_column("File Path", style="yellow")
table.add_column("Type", style="green")
for entity in entities:
table.add_row(
entity.title,
entity.file_path,
entity.note_type or "",
table = Table(
title=f"{project_name}: Entities Without Relations ({len(entities)} total)"
)
table.add_column("Title", style="cyan")
table.add_column("File Path", style="yellow")
table.add_column("Type", style="green")
console.print(table)
except (ValueError, ToolError) as exc:
if json_output:
print(json.dumps({"error": str(exc)}, indent=2))
else:
console.print(f"[red]Error: {exc}[/red]")
raise typer.Exit(code=1)
except typer.Exit:
for entity in entities:
table.add_row(
entity.get("title", ""),
entity.get("file_path", ""),
entity.get("note_type") or "",
)
console.print(table)
except (ValueError, typer.Exit):
raise
except Exception as exc:
logger.error(f"Error fetching orphan entities: {exc}")
except Exception as e:
logger.error(f"Error fetching orphan entities: {e}")
if json_output:
print(json.dumps({"error": str(exc)}, indent=2))
print(json.dumps({"error": str(e)}, indent=2))
else:
console.print(f"[red]Error: {exc}[/red]")
console.print(f"[red]Error: {e}[/red]")
raise typer.Exit(code=1) # pragma: no cover
+59 -363
View File
@@ -7,7 +7,6 @@ from pathlib import Path
from typing import cast
import typer
from loguru import logger
from rich.console import Console, Group
from rich.panel import Panel
from rich.table import Table
@@ -27,17 +26,13 @@ from basic_memory.cli.commands.cloud.rclone_commands import (
)
from basic_memory.cli.commands.command_utils import get_project_info, run_with_cleanup
from basic_memory.cli.commands.routing import force_routing, validate_routing_flags
from basic_memory.config import BasicMemoryConfig, ConfigManager, ProjectEntry, ProjectMode
from basic_memory.config import ConfigManager, ProjectEntry, ProjectMode
from basic_memory.mcp.async_client import get_client, resolve_configured_workspace
from basic_memory.mcp.clients import ProjectClient
from basic_memory.schemas.cloud import (
CloudProjectIndexStatus,
CloudTenantIndexStatusResponse,
ProjectVisibility,
WorkspaceInfo,
format_workspace_choices,
format_workspace_selection_choices,
workspace_matches_identifier,
)
from basic_memory.schemas.project_info import ProjectItem, ProjectList
from basic_memory.utils import generate_permalink, normalize_project_path
@@ -286,25 +281,27 @@ def _normalize_project_visibility(visibility: str | None) -> ProjectVisibility:
def _resolve_workspace_id(config, workspace: str | None) -> str | None:
"""Resolve a workspace name, slug, type, or tenant_id to a tenant_id."""
"""Resolve a workspace name or tenant_id to a tenant_id."""
from basic_memory.mcp.project_context import (
_workspace_choices,
_workspace_matches_identifier,
get_available_workspaces,
)
if workspace is not None:
workspaces = run_with_cleanup(get_available_workspaces())
matches = [ws for ws in workspaces if workspace_matches_identifier(ws, workspace)]
matches = [ws for ws in workspaces if _workspace_matches_identifier(ws, workspace)]
if not matches:
console.print(f"[red]Error: Workspace '{workspace}' not found[/red]")
if workspaces:
console.print(f"[dim]Available:\n{format_workspace_choices(workspaces)}[/dim]")
console.print(f"[dim]Available:\n{_workspace_choices(workspaces)}[/dim]")
raise typer.Exit(1)
if len(matches) > 1:
console.print(f"[red]Error: Workspace '{workspace}' matches multiple workspaces.[/red]")
console.print(
"[dim]Choose one of these matching workspaces by slug:\n"
f"{format_workspace_selection_choices(matches)}[/dim]"
f"[red]Error: Workspace name '{workspace}' matches multiple workspaces. "
f"Use tenant_id instead.[/red]"
)
console.print(f"[dim]Available:\n{_workspace_choices(workspaces)}[/dim]")
raise typer.Exit(1)
return matches[0].tenant_id
@@ -315,9 +312,9 @@ def _resolve_workspace_id(config, workspace: str | None) -> str | None:
workspaces = run_with_cleanup(get_available_workspaces())
if len(workspaces) == 1:
return workspaces[0].tenant_id
except Exception as exc:
except Exception:
# Workspace resolution is optional until a command needs a specific tenant.
logger.debug("Workspace resolution failed: {}", exc)
pass
return None
@@ -326,11 +323,7 @@ def _resolve_workspace_id(config, workspace: str | None) -> str | None:
def list_projects(
local: bool = typer.Option(False, "--local", help="Force local routing for this command"),
cloud: bool = typer.Option(False, "--cloud", help="Force cloud API routing"),
workspace: str = typer.Option(
None,
"--workspace",
help="Cloud workspace name, slug, type, or tenant_id",
),
workspace: str = typer.Option(None, "--workspace", help="Cloud workspace name or tenant_id"),
json_output: bool = typer.Option(False, "--json", help="Output in JSON format"),
) -> None:
"""List Basic Memory projects from local and (when available) cloud."""
@@ -346,90 +339,17 @@ def list_projects(
try:
config = ConfigManager().config
workspace_filter = workspace
workspace_filter_requested = workspace_filter is not None
# Use explicit workspace, fall back to config default
effective_workspace = workspace or config.default_workspace
local_result: ProjectList | None = None
cloud_results: list[tuple[WorkspaceInfo | None, ProjectList]] = []
available_cloud_workspaces: list[WorkspaceInfo] = []
cloud_result: ProjectList | None = None
cloud_error: Exception | None = None
cloud_workspace_error: Exception | None = None
failed_cloud_workspaces: list[tuple[WorkspaceInfo, Exception]] = []
def _fetch_cloud_workspace_results() -> tuple[
list[tuple[WorkspaceInfo | None, ProjectList]],
list[WorkspaceInfo],
Exception | None,
list[tuple[WorkspaceInfo, Exception]],
]:
from basic_memory.mcp.project_context import (
get_available_workspaces,
)
try:
workspaces = run_with_cleanup(get_available_workspaces())
except Exception as exc:
fallback_workspace = workspace_filter or config.default_workspace
return (
[(None, run_with_cleanup(_list_projects(fallback_workspace)))],
[],
exc,
[],
)
selected_workspaces = workspaces
if workspace_filter is not None:
matches = [
ws for ws in workspaces if workspace_matches_identifier(ws, workspace_filter)
]
if not matches:
console.print(f"[red]Error: Workspace '{workspace_filter}' not found[/red]")
if workspaces:
console.print(
f"[dim]Available:\n{format_workspace_choices(workspaces)}[/dim]"
)
raise typer.Exit(1)
if len(matches) > 1:
console.print(
f"[red]Error: Workspace '{workspace_filter}' matches multiple workspaces.[/red]"
)
console.print(
"[dim]Choose one of these matching workspaces by slug:\n"
f"{format_workspace_selection_choices(matches)}[/dim]"
)
raise typer.Exit(1)
selected_workspaces = matches
if not selected_workspaces:
return [], workspaces, None, []
results: list[tuple[WorkspaceInfo | None, ProjectList]] = []
failed_workspaces: list[tuple[WorkspaceInfo, Exception]] = []
for cloud_workspace in selected_workspaces:
try:
results.append(
(
cloud_workspace,
run_with_cleanup(_list_projects(cloud_workspace.tenant_id)),
)
)
except Exception as exc:
failed_workspaces.append((cloud_workspace, exc))
if not results and failed_workspaces:
raise failed_workspaces[0][1]
return results, workspaces, None, failed_workspaces
if cloud:
with console.status("[bold blue]Fetching cloud projects...", spinner="dots"):
with force_routing(cloud=True):
(
cloud_results,
available_cloud_workspaces,
cloud_workspace_error,
failed_cloud_workspaces,
) = _fetch_cloud_workspace_results()
cloud_result = run_with_cleanup(_list_projects(effective_workspace))
elif local:
with force_routing(local=True):
local_result = run_with_cleanup(_list_projects())
@@ -442,17 +362,29 @@ def list_projects(
try:
with console.status("[bold blue]Fetching cloud projects...", spinner="dots"):
with force_routing(cloud=True):
(
cloud_results,
available_cloud_workspaces,
cloud_workspace_error,
failed_cloud_workspaces,
) = _fetch_cloud_workspace_results()
except typer.Exit:
raise
cloud_result = run_with_cleanup(_list_projects(effective_workspace))
except Exception as exc: # pragma: no cover
cloud_error = exc
# Resolve workspace name for cloud projects (best-effort)
cloud_ws_name: str | None = None
cloud_ws_type: str | None = None
if cloud_result and effective_workspace:
try:
from basic_memory.mcp.project_context import get_available_workspaces
with console.status("[bold blue]Resolving workspace...", spinner="dots"):
workspaces = run_with_cleanup(get_available_workspaces())
matched = next(
(ws for ws in workspaces if ws.tenant_id == effective_workspace),
None,
)
if matched:
cloud_ws_name = matched.name
cloud_ws_type = matched.workspace_type
except Exception:
pass
table = Table(title="Basic Memory Projects")
table.add_column("Name", style="cyan")
table.add_column("Local Path", style="yellow", no_wrap=True, overflow="fold")
@@ -463,126 +395,29 @@ def list_projects(
table.add_column("Sync", style="green")
table.add_column("Default", style="magenta")
row_names_by_key: dict[tuple[str | None, str], str] = {}
project_names_by_permalink: dict[str, str] = {}
local_projects_by_permalink: dict[str, ProjectItem] = {}
cloud_projects_by_key: dict[tuple[str | None, str], ProjectItem] = {}
cloud_workspaces_by_key: dict[tuple[str | None, str], WorkspaceInfo | None] = {}
cloud_projects_by_permalink: dict[str, ProjectItem] = {}
if local_result:
for project in local_result.projects:
permalink = generate_permalink(project.name)
project_names_by_permalink[permalink] = project.name
local_projects_by_permalink[permalink] = project
for cloud_workspace, cloud_result in cloud_results:
workspace_key = cloud_workspace.tenant_id if cloud_workspace else None
if cloud_result:
for project in cloud_result.projects:
permalink = generate_permalink(project.name)
row_key = (workspace_key, permalink)
row_names_by_key[row_key] = project.name
cloud_projects_by_key[row_key] = project
cloud_workspaces_by_key[row_key] = cloud_workspace
cloud_permalinks = {permalink for _, permalink in cloud_projects_by_key}
for permalink, project in local_projects_by_permalink.items():
if permalink not in cloud_permalinks:
row_names_by_key[(None, permalink)] = project.name
cloud_keys_by_permalink: dict[str, list[tuple[str | None, str]]] = {}
for row_key in cloud_projects_by_key:
cloud_keys_by_permalink.setdefault(row_key[1], []).append(row_key)
configured_names_by_permalink = {
generate_permalink(project_name): project_name for project_name in config.projects
}
def _workspace_priority(row_key: tuple[str | None, str]) -> tuple[bool, int, str, str]:
"""Prefer the user's default/personal workspace when a project is duplicated."""
workspace = cloud_workspaces_by_key.get(row_key)
if workspace is None:
return (True, 2, "", row_key[0] or "")
workspace_type_rank = 0 if workspace.workspace_type == "personal" else 1
return (
not workspace.is_default,
workspace_type_rank,
workspace.name.casefold(),
row_key[0] or "",
)
def _select_attached_row_key(
permalink: str, entry: ProjectEntry | None
) -> tuple[str | None, str] | None:
"""Choose the single row that owns local config/default/sync state."""
cloud_keys = cloud_keys_by_permalink.get(permalink, [])
if not cloud_keys:
return (None, permalink)
preferred_workspace_ids: list[str] = []
if entry and entry.workspace_id:
preferred_workspace_ids.append(entry.workspace_id)
if config.default_workspace and config.default_workspace not in preferred_workspace_ids:
preferred_workspace_ids.append(config.default_workspace)
default_cloud_workspace = next(
(item for item in available_cloud_workspaces if item.is_default),
None,
)
if (
default_cloud_workspace
and default_cloud_workspace.tenant_id not in preferred_workspace_ids
):
preferred_workspace_ids.append(default_cloud_workspace.tenant_id)
for workspace_id in preferred_workspace_ids:
for row_key in cloud_keys:
if row_key[0] == workspace_id:
return row_key
if workspace_filter_requested and preferred_workspace_ids:
# A filtered list can exclude the workspace that owns local config state.
# In that case, do not attach local/default/sync state to another workspace row.
return None
default_workspace_keys = [
row_key
for row_key in cloud_keys
if (row_workspace := cloud_workspaces_by_key.get(row_key)) is not None
and row_workspace.is_default
]
if len(default_workspace_keys) == 1:
return default_workspace_keys[0]
if len(cloud_keys) == 1:
return cloud_keys[0]
return sorted(cloud_keys, key=_workspace_priority)[0]
attached_row_by_permalink: dict[str, tuple[str | None, str] | None] = {}
for permalink in set(local_projects_by_permalink) | set(configured_names_by_permalink):
configured_name = configured_names_by_permalink.get(permalink)
local_project = local_projects_by_permalink.get(permalink)
entry_name = configured_name or (local_project.name if local_project else None)
entry = config.projects.get(entry_name) if entry_name else None
attached_row_by_permalink[permalink] = _select_attached_row_key(permalink, entry)
project_names_by_permalink[permalink] = project.name
cloud_projects_by_permalink[permalink] = project
# --- Build unified project list ---
project_rows: list[dict] = []
sorted_row_keys = sorted(
row_names_by_key,
key=lambda key: (row_names_by_key[key], key[0] or ""),
)
for row_key in sorted_row_keys:
_, permalink = row_key
project_name = row_names_by_key[row_key]
is_attached_row = attached_row_by_permalink.get(permalink) == row_key
local_project = local_projects_by_permalink.get(permalink) if is_attached_row else None
cloud_project = cloud_projects_by_key.get(row_key)
cloud_workspace = cloud_workspaces_by_key.get(row_key)
configured_name = configured_names_by_permalink.get(permalink)
configured_entry = (
config.projects.get(configured_name)
if configured_name
else config.projects.get(project_name)
)
entry = configured_entry if is_attached_row else None
for permalink in sorted(project_names_by_permalink):
project_name = project_names_by_permalink[permalink]
local_project = local_projects_by_permalink.get(permalink)
cloud_project = cloud_projects_by_permalink.get(permalink)
entry = config.projects.get(project_name)
local_path = ""
if local_project is not None:
@@ -612,13 +447,9 @@ def list_projects(
else:
cli_route = ProjectMode.LOCAL.value
default_permalink = (
generate_permalink(config.default_project) if config.default_project else None
)
is_default = bool(is_attached_row and permalink == default_permalink)
is_default = config.default_project == project_name
sync_supported = cloud_workspace is None or cloud_workspace.workspace_type == "personal"
has_sync = bool(is_attached_row and entry and entry.local_sync_path and sync_supported)
has_sync = bool(entry and entry.local_sync_path)
# Determine MCP transport based on project routing mode
if entry and entry.mode == ProjectMode.CLOUD:
mcp_transport = "https"
@@ -628,8 +459,9 @@ def list_projects(
mcp_transport = "stdio"
# Show workspace name (type) for cloud-sourced projects
cloud_ws_name = cloud_workspace.name if cloud_workspace else None
cloud_ws_type = cloud_workspace.workspace_type if cloud_workspace else None
ws_label = ""
if cloud_project is not None and cloud_ws_name:
ws_label = f"{cloud_ws_name} ({cloud_ws_type})" if cloud_ws_type else cloud_ws_name
# display_name is a human label for private UUID-named projects (e.g., "My Project").
# Keep "name" as the canonical identifier for scripting/JSON consumers;
@@ -649,8 +481,8 @@ def list_projects(
}
if display_name:
row_data["display_name"] = display_name
if cloud_project is not None and cloud_ws_name:
row_data["workspace"] = cloud_ws_name
if ws_label:
row_data["workspace"] = cloud_ws_name or ""
if cloud_ws_type:
row_data["workspace_type"] = cloud_ws_type
@@ -682,20 +514,6 @@ def list_projects(
"[dim]Showing local projects only. "
"Run 'bm cloud login' or 'bm cloud api-key save <key>' if this is a credentials issue.[/dim]"
)
if cloud_workspace_error is not None:
console.print(
f"[yellow]Cloud workspace discovery failed: {cloud_workspace_error}[/yellow]"
)
console.print(
"[dim]Showing cloud projects from the configured/default workspace only.[/dim]"
)
for failed_workspace, error in failed_cloud_workspaces:
console.print(
f"[yellow]Cloud project discovery failed for workspace "
f"{failed_workspace.name}: {error}[/yellow]"
)
except typer.Exit:
raise
except Exception as e:
console.print(f"[red]Error listing projects: {str(e)}[/red]")
raise typer.Exit(1)
@@ -713,7 +531,7 @@ def add_project(
workspace: str = typer.Option(
None,
"--workspace",
help="Cloud workspace name, slug, type, or tenant_id (cloud mode only)",
help="Cloud workspace name or tenant_id (cloud mode only)",
),
visibility: str = typer.Option(
None,
@@ -1020,83 +838,13 @@ def move_project(
raise typer.Exit(1)
async def _detach_local_project_row(app_config: BasicMemoryConfig, name: str) -> bool:
"""Drop the project's row from the local index DB.
Trigger: `bm project set-cloud` is making a project cloud-only.
Why: the local row is what causes `_merge_projects` to report
`source: "local+cloud"` after the toggle (#680). Removing it
forces the merged listing to honor the user's chosen mode.
Outcome: returns True if a row was deleted, False if there was
nothing to clean up. On-disk note files are not touched.
"""
from basic_memory import db
from basic_memory.repository import ProjectRepository
_, session_maker = await db.get_or_create_db(
db_path=app_config.database_path,
db_type=db.DatabaseType.FILESYSTEM,
)
try:
repo = ProjectRepository(session_maker)
existing = await repo.get_by_name(name)
if existing is None:
return False
await repo.delete(existing.id)
return True
finally:
# CLI-only: safe to tear down the global DB singleton here since
# set-cloud/set-local never run inside a long-lived MCP/API server.
await db.shutdown_db()
async def _attach_local_project_row(app_config: BasicMemoryConfig, name: str, path: str) -> None:
"""Ensure the project has a row in the local index DB at the given path.
Trigger: `bm project set-local` is making a previously cloud-only
project local again.
Why: without a row in the local DB, every local-side tool (`list`,
`info`, sync, indexing) would skip this project.
Outcome: a row is created if missing, or its path is updated to match
the new local home if it already exists. On-disk files are not
touched — the caller is responsible for ensuring the directory
exists.
"""
from basic_memory import db
from basic_memory.repository import ProjectRepository
_, session_maker = await db.get_or_create_db(
db_path=app_config.database_path,
db_type=db.DatabaseType.FILESYSTEM,
)
try:
repo = ProjectRepository(session_maker)
existing = await repo.get_by_name(name)
if existing is None:
await repo.create(
{
"name": name,
"path": path,
"permalink": generate_permalink(name),
"is_active": True,
}
)
return
if existing.path != path:
await repo.update_path(existing.id, path)
finally:
# CLI-only: safe to tear down the global DB singleton here since
# set-cloud/set-local never run inside a long-lived MCP/API server.
await db.shutdown_db()
@project_app.command("set-cloud")
def set_cloud(
name: str = typer.Argument(..., help="Name of the project to route through cloud"),
workspace: str = typer.Option(
None,
"--workspace",
help="Cloud workspace name, slug, type, or tenant_id to associate with this project",
help="Cloud workspace name or tenant_id to associate with this project",
),
) -> None:
"""Set a project to cloud mode (route through cloud API).
@@ -1107,13 +855,6 @@ def set_cloud(
If omitted, uses the default workspace (if set) or auto-selects when
only one workspace is available.
This is a one-way cutover: the project's row in the local index DB is
removed and the local path in config is cleared so the project's
configured state is purely cloud. On-disk note files are preserved —
the caller can keep, archive, or delete them as they see fit. To
return to local mode use `bm project set-local <name> --local-path
<path>`.
Examples:
bm project set-cloud research --workspace Personal
bm project set-cloud research --workspace 11111111-...
@@ -1142,52 +883,27 @@ def set_cloud(
resolved_workspace_id = _resolve_workspace_id(config, workspace)
# Drop the local DB row first so the user-visible state stays consistent
# even if the config save below raises for some reason. Idempotent: a
# second `set-cloud` simply finds no row and returns False.
previous_path = config.projects[name].path
detached = run_with_cleanup(_detach_local_project_row(config, name))
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
config.projects[name].path = ""
config_manager.save_config(config)
console.print(f"[green]Project '{name}' set to cloud mode[/green]")
if resolved_workspace_id:
console.print(f"[dim]Workspace: {resolved_workspace_id}[/dim]")
if detached and previous_path:
console.print(
f"[dim]Local index entry removed. Files at {previous_path} are preserved on disk.[/dim]"
)
console.print("[dim]MCP tools and CLI commands for this project will route through cloud[/dim]")
@project_app.command("set-local")
def set_local(
name: str = typer.Argument(..., help="Name of the project to revert to local mode"),
local_path: str = typer.Option(
None,
"--local-path",
help=(
"Local filesystem path for this project. Required unless the project "
"was previously local and its prior path is still in config."
),
),
) -> None:
"""Revert a project to local mode (use in-process ASGI transport).
Recreates the project's row in the local index DB and clears any
associated cloud workspace. If the project was previously local and
its prior path is still in config (e.g. an older version that didn't
blank `path` on `set-cloud`), `--local-path` may be omitted and that
path will be reused.
Clears any associated cloud workspace.
Examples:
bm project set-local research --local-path ~/Documents/research
bm project set-local research # reuse prior path
Example:
bm project set-local research
"""
config_manager = ConfigManager()
config = config_manager.config
@@ -1197,31 +913,11 @@ def set_local(
console.print(f"[red]Error: Project '{name}' not found in config[/red]")
raise typer.Exit(1)
entry = config.projects[name]
candidate = local_path or entry.path
if not candidate:
console.print(
f"[red]Error: --local-path is required for '{name}' "
"(no previous local path is recorded)[/red]"
)
raise typer.Exit(1)
resolved_path = Path(os.path.abspath(os.path.expanduser(candidate))).as_posix()
# Recreate the local DB row. Idempotent: if the row exists with the
# same path it's a no-op; if it exists at a stale path the path is
# updated. The directory itself is not auto-created — the user is
# expected to know whether they want to start a fresh project tree
# or point at an existing one.
run_with_cleanup(_attach_local_project_row(config, name, resolved_path))
config.set_project_mode(name, ProjectMode.LOCAL)
config.projects[name].workspace_id = None
config.projects[name].path = resolved_path
config_manager.save_config(config)
console.print(f"[green]Project '{name}' set to local mode[/green]")
console.print(f"[dim]Path: {resolved_path}[/dim]")
console.print("[dim]MCP tools and CLI commands for this project will use local transport[/dim]")
+32 -54
View File
@@ -62,12 +62,9 @@ def write_note(
help="The project to write to. If not provided, the default project will be used."
),
] = None,
project_id: Annotated[
workspace: Annotated[
Optional[str],
typer.Option(
"--project-id",
help="Project external_id (UUID). Takes precedence over --project; use to disambiguate same-named projects across cloud workspaces.",
),
typer.Option(help="Cloud workspace tenant ID or unique name to route this request."),
] = None,
local: bool = typer.Option(
False, "--local", help="Force local API routing (ignore cloud mode)"
@@ -109,7 +106,7 @@ def write_note(
content=content,
directory=folder,
project=project,
project_id=project_id,
workspace=workspace,
tags=tags,
output_format="json",
)
@@ -131,16 +128,15 @@ def read_note(
include_frontmatter: bool = typer.Option(
False, "--include-frontmatter", help="Include YAML frontmatter in output"
),
page: int = typer.Option(1, "--page", help="Page number for pagination"),
page_size: int = typer.Option(10, "--page-size", help="Number of results per page"),
project: Annotated[
Optional[str],
typer.Option(help="The project to use. If not provided, the default project will be used."),
] = None,
project_id: Annotated[
workspace: Annotated[
Optional[str],
typer.Option(
"--project-id",
help="Project external_id (UUID). Takes precedence over --project; use to disambiguate same-named projects across cloud workspaces.",
),
typer.Option(help="Cloud workspace tenant ID or unique name to route this request."),
] = None,
local: bool = typer.Option(
False, "--local", help="Force local API routing (ignore cloud mode)"
@@ -153,6 +149,7 @@ def read_note(
bm tool read-note my-note
bm tool read-note my-note --include-frontmatter
bm tool read-note my-note --page 2 --page-size 5
"""
try:
validate_routing_flags(local, cloud)
@@ -162,7 +159,9 @@ def read_note(
mcp_read_note(
identifier=identifier,
project=project,
project_id=project_id,
workspace=workspace,
page=page,
page_size=page_size,
include_frontmatter=include_frontmatter,
output_format="json",
)
@@ -201,12 +200,9 @@ def edit_note(
help="The project to edit. If not provided, the default project will be used."
),
] = None,
project_id: Annotated[
workspace: Annotated[
Optional[str],
typer.Option(
"--project-id",
help="Project external_id (UUID). Takes precedence over --project; use to disambiguate same-named projects across cloud workspaces.",
),
typer.Option(help="Cloud workspace tenant ID or unique name to route this request."),
] = None,
local: bool = typer.Option(
False, "--local", help="Force local API routing (ignore cloud mode)"
@@ -231,7 +227,7 @@ def edit_note(
operation=operation,
content=content,
project=project,
project_id=project_id,
workspace=workspace,
section=section,
find_text=find_text,
expected_replacements=expected_replacements,
@@ -269,12 +265,9 @@ def build_context(
Optional[str],
typer.Option(help="The project to use. If not provided, the default project will be used."),
] = None,
project_id: Annotated[
workspace: Annotated[
Optional[str],
typer.Option(
"--project-id",
help="Project external_id (UUID). Takes precedence over --project; use to disambiguate same-named projects across cloud workspaces.",
),
typer.Option(help="Cloud workspace tenant ID or unique name to route this request."),
] = None,
local: bool = typer.Option(
False, "--local", help="Force local API routing (ignore cloud mode)"
@@ -296,7 +289,7 @@ def build_context(
mcp_build_context(
url=url,
project=project,
project_id=project_id,
workspace=workspace,
depth=depth,
timeframe=timeframe,
page=page,
@@ -329,12 +322,9 @@ def recent_activity(
Optional[str],
typer.Option(help="The project to use. If not provided, the default project will be used."),
] = None,
project_id: Annotated[
workspace: Annotated[
Optional[str],
typer.Option(
"--project-id",
help="Project external_id (UUID). Takes precedence over --project; use to disambiguate same-named projects across cloud workspaces.",
),
typer.Option(help="Cloud workspace tenant ID or unique name to route this request."),
] = None,
local: bool = typer.Option(
False, "--local", help="Force local API routing (ignore cloud mode)"
@@ -361,7 +351,7 @@ def recent_activity(
page=page,
page_size=page_size,
project=project,
project_id=project_id,
workspace=workspace,
output_format="json",
)
)
@@ -423,12 +413,9 @@ def search_notes(
Optional[str],
typer.Option(help="The project to use. If not provided, the default project will be used."),
] = None,
project_id: Annotated[
workspace: Annotated[
Optional[str],
typer.Option(
"--project-id",
help="Project external_id (UUID). Takes precedence over --project; use to disambiguate same-named projects across cloud workspaces.",
),
typer.Option(help="Cloud workspace tenant ID or unique name to route this request."),
] = None,
local: bool = typer.Option(
False, "--local", help="Force local API routing (ignore cloud mode)"
@@ -500,7 +487,7 @@ def search_notes(
mcp_search(
query=query or None,
project=project,
project_id=project_id,
workspace=workspace,
search_type=search_type,
output_format="json",
page=page,
@@ -610,12 +597,9 @@ def schema_validate(
Optional[str],
typer.Option(help="The project to use. If not provided, the default project will be used."),
] = None,
project_id: Annotated[
workspace: Annotated[
Optional[str],
typer.Option(
"--project-id",
help="Project external_id (UUID). Takes precedence over --project; use to disambiguate same-named projects across cloud workspaces.",
),
typer.Option(help="Cloud workspace tenant ID or unique name to route this request."),
] = None,
local: bool = typer.Option(
False, "--local", help="Force local API routing (ignore cloud mode)"
@@ -650,7 +634,7 @@ def schema_validate(
note_type=note_type,
identifier=identifier,
project=project,
project_id=project_id,
workspace=workspace,
output_format="json",
)
)
@@ -681,12 +665,9 @@ def schema_infer(
Optional[str],
typer.Option(help="The project to use. If not provided, the default project will be used."),
] = None,
project_id: Annotated[
workspace: Annotated[
Optional[str],
typer.Option(
"--project-id",
help="Project external_id (UUID). Takes precedence over --project; use to disambiguate same-named projects across cloud workspaces.",
),
typer.Option(help="Cloud workspace tenant ID or unique name to route this request."),
] = None,
local: bool = typer.Option(
False, "--local", help="Force local API routing (ignore cloud mode)"
@@ -710,7 +691,7 @@ def schema_infer(
note_type=note_type,
threshold=threshold,
project=project,
project_id=project_id,
workspace=workspace,
output_format="json",
)
)
@@ -738,12 +719,9 @@ def schema_diff(
Optional[str],
typer.Option(help="The project to use. If not provided, the default project will be used."),
] = None,
project_id: Annotated[
workspace: Annotated[
Optional[str],
typer.Option(
"--project-id",
help="Project external_id (UUID). Takes precedence over --project; use to disambiguate same-named projects across cloud workspaces.",
),
typer.Option(help="Cloud workspace tenant ID or unique name to route this request."),
] = None,
local: bool = typer.Option(
False, "--local", help="Force local API routing (ignore cloud mode)"
@@ -765,7 +743,7 @@ def schema_diff(
mcp_schema_diff(
note_type=note_type,
project=project,
project_id=project_id,
workspace=workspace,
output_format="json",
)
)
+12 -41
View File
@@ -21,27 +21,13 @@ from basic_memory.utils import setup_logging, generate_permalink
DATABASE_NAME = "memory.db"
APP_DATABASE_NAME = "memory.db" # Using the same name but in the app directory
DATA_DIR_NAME = "basic-memory"
DATA_DIR_NAME = ".basic-memory"
CONFIG_FILE_NAME = "config.json"
WATCH_STATUS_JSON = "watch-status.json"
CONFIG_DIR_MODE = 0o700
CONFIG_FILE_MODE = 0o600
Environment = Literal["test", "dev", "user"]
def _secure_config_dir(path: Path) -> None:
"""Restrict config directory permissions on platforms with POSIX modes."""
if os.name != "nt":
path.chmod(CONFIG_DIR_MODE)
def _secure_config_file(path: Path) -> None:
"""Restrict config file permissions because config can contain cloud credentials."""
if os.name != "nt":
path.chmod(CONFIG_FILE_MODE)
class ProjectMode(str, Enum):
"""Per-project routing mode."""
@@ -69,18 +55,15 @@ def resolve_data_dir() -> Path:
Single source of truth for the per-user state directory. Honors
``BASIC_MEMORY_CONFIG_DIR`` so each process/worktree can isolate config
and database state; otherwise falls back to ``<user home>/.basic-memory``,
and then to ``XDG_CONFIG_HOME``.
and database state; otherwise falls back to ``<user home>/.basic-memory``.
Cross-platform: ``Path.home()`` reads ``$HOME`` on POSIX and
``%USERPROFILE%`` on Windows, so there's no need to check ``$HOME``
explicitly here.
"""
if basic_memory_dir := os.getenv("BASIC_MEMORY_CONFIG_DIR"):
return Path(basic_memory_dir)
if xdg_config := os.getenv("XDG_CONFIG_HOME"):
return Path(xdg_config) / DATA_DIR_NAME
return Path.home() / ("." + DATA_DIR_NAME)
if config_dir := os.getenv("BASIC_MEMORY_CONFIG_DIR"):
return Path(config_dir)
return Path.home() / DATA_DIR_NAME
def default_fastembed_cache_dir() -> str:
@@ -185,15 +168,13 @@ class BasicMemoryConfig(BaseSettings):
env: Environment = Field(default="dev", description="Environment name")
projects: Dict[str, ProjectEntry] = Field(
default_factory=lambda: (
{
"main": ProjectEntry(
path=str(Path(os.getenv("BASIC_MEMORY_HOME", Path.home() / "basic-memory")))
)
}
if os.getenv("BASIC_MEMORY_HOME")
else {}
),
default_factory=lambda: {
"main": ProjectEntry(
path=str(Path(os.getenv("BASIC_MEMORY_HOME", Path.home() / "basic-memory")))
)
}
if os.getenv("BASIC_MEMORY_HOME")
else {},
description="Mapping of project names to their ProjectEntry configuration",
)
default_project: Optional[str] = Field(
@@ -297,11 +278,6 @@ class BasicMemoryConfig(BaseSettings):
description="Optional FastEmbed embed() parallelism override.",
gt=0,
)
import_upload_max_bytes: int = Field(
default=100 * 1024 * 1024,
description="Maximum uploaded JSON export size accepted by API import endpoints.",
gt=0,
)
semantic_vector_k: int = Field(
default=100,
description="Vector candidate count for vector and hybrid retrieval.",
@@ -800,7 +776,6 @@ class ConfigManager:
# Ensure config directory exists
self.config_dir.mkdir(parents=True, exist_ok=True)
_secure_config_dir(self.config_dir)
@property
def config(self) -> BasicMemoryConfig:
@@ -913,7 +888,6 @@ class ConfigManager:
# Create backup before overwriting so users can revert if needed
backup_path = self.config_file.with_suffix(".json.bak")
shutil.copy2(self.config_file, backup_path)
_secure_config_file(backup_path)
logger.info(f"Migrating config to current format (backup: {backup_path})")
save_basic_memory_config(self.config_file, _CONFIG_CACHE)
@@ -1069,12 +1043,9 @@ def has_cloud_credentials(config: BasicMemoryConfig) -> bool:
def save_basic_memory_config(file_path: Path, config: BasicMemoryConfig) -> None:
"""Save configuration to file."""
try:
file_path.parent.mkdir(parents=True, exist_ok=True)
_secure_config_dir(file_path.parent)
# Use model_dump with mode='json' to serialize datetime objects properly
config_dict = config.model_dump(mode="json")
file_path.write_text(json.dumps(config_dict, indent=2))
_secure_config_file(file_path)
except Exception as e: # pragma: no cover
logger.error(f"Failed to save config: {e}")
-4
View File
@@ -447,12 +447,8 @@ class TaskScheduler(Protocol):
def _log_task_failure(completed: asyncio.Task) -> None:
if completed.cancelled():
return
try:
completed.result()
except asyncio.CancelledError:
return
except Exception as exc: # pragma: no cover
logger.exception("Background task failed", error=str(exc))
+8 -45
View File
@@ -85,28 +85,6 @@ def parse_observation(token: Token) -> Dict[str, Any]:
# Relation handling functions
def parse_relation_type(content: str) -> str | None:
"""Return the explicit relation label before the first wikilink, if any."""
before_link = content.partition("[[")[0].strip()
if not before_link:
return None
# Trigger: relation labels that need spaces must be quoted.
# Why: unquoted multi-word prefixes are indistinguishable from prose
# containing a wikilink.
# Outcome: `some_type [[Target]]`, `"some type" [[Target]]`, and
# `'some type' [[Target]]` are explicit; `some other thing [[Target]]`
# falls back to inline `links_to` handling.
quote = before_link[0]
if quote in {"'", '"'} and before_link.endswith(quote):
quoted_label = before_link[1:-1].strip()
return quoted_label or None
if any(char.isspace() for char in before_link):
return None
return before_link
def is_explicit_relation(token: Token) -> bool:
"""Check if token looks like our relation format."""
if token.type != "inline": # pragma: no cover
@@ -114,7 +92,7 @@ def is_explicit_relation(token: Token) -> bool:
# Use token.tag which contains the actual content for test tokens, fallback to content
content = (token.tag or token.content).strip()
return "[[" in content and "]]" in content and parse_relation_type(content) is not None
return "[[" in content and "]]" in content
def parse_relation(token: Token) -> Dict[str, Any] | None:
@@ -123,18 +101,20 @@ def parse_relation(token: Token) -> Dict[str, Any] | None:
# Use token.tag which contains the actual content for test tokens, fallback to content
content = (token.tag or token.content).strip()
rel_type = parse_relation_type(content)
if rel_type is None:
return None
# Extract [[target]]
target = None
rel_type = "relates_to" # default
context = None
start = content.find("[[")
end = content.find("]]", start + 2)
end = content.find("]]")
if start != -1 and end != -1:
# Get text before link as relation type
before = content[:start].strip()
if before:
rel_type = before
# Get target
target = normalize_project_reference(content[start + 2 : end].strip())
@@ -200,9 +180,6 @@ def observation_plugin(md: MarkdownIt) -> None:
def observation_rule(state: Any) -> None:
"""Process observations in token stream."""
tokens = state.tokens
# Track blockquote nesting so Obsidian callouts (`> [!info] Title`)
# don't get parsed as observations with category `!info`.
blockquote_depth = 0
for idx in range(len(tokens)):
token = tokens[idx]
@@ -210,18 +187,6 @@ def observation_plugin(md: MarkdownIt) -> None:
# Initialize meta for all tokens
token.meta = token.meta or {}
if token.type == "blockquote_open":
blockquote_depth += 1
continue
if token.type == "blockquote_close":
blockquote_depth -= 1
continue
# Skip parsing inside blockquotes — that's Obsidian callout
# territory, not Basic Memory observation syntax.
if blockquote_depth > 0:
continue
# Parse observations in list items
if token.type == "inline" and is_observation(token):
obs = parse_observation(token)
@@ -237,8 +202,6 @@ def relation_plugin(md: MarkdownIt) -> None:
Explicit relations:
- relation_type [[target]] (context)
- "multi word relation type" [[target]] (context)
- 'multi word relation type' [[target]] (context)
Implicit relations (links in content):
Some text with [[target]] reference
+8 -208
View File
@@ -1,36 +1,14 @@
import os
from asyncio import Lock
from contextlib import AbstractAsyncContextManager, AsyncExitStack, asynccontextmanager
from dataclasses import dataclass
from threading import RLock
from typing import TYPE_CHECKING, Annotated, Any, AsyncIterator, Callable, Optional
from contextlib import AbstractAsyncContextManager, asynccontextmanager
from typing import AsyncIterator, Callable, Optional
from fastapi import Depends, FastAPI, Request
from httpx import ASGITransport, AsyncClient, Timeout
from loguru import logger
import logfire
from basic_memory.api.app import app as fastapi_app
from basic_memory.config import ConfigManager, ProjectMode
if TYPE_CHECKING:
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker
LocalDatabaseState = tuple["AsyncEngine", "async_sessionmaker[AsyncSession]"]
_MISSING_STATE_VALUE = object()
@dataclass
class _PreparedLocalAsgiDatabase:
active_count: int
previous_engine: object
previous_session_maker: object
dependency_context: AbstractAsyncContextManager[LocalDatabaseState]
_prepared_local_asgi_database_lock = RLock()
_prepared_local_asgi_database_prepare_locks: dict[FastAPI, Lock] = {}
_prepared_local_asgi_databases: dict[FastAPI, _PreparedLocalAsgiDatabase] = {}
def _force_local_mode() -> bool:
"""Check if local mode is forced via environment variable."""
@@ -57,181 +35,11 @@ def _build_timeout() -> Timeout:
)
def _build_asgi_client(app: FastAPI, timeout: Timeout) -> AsyncClient:
"""Create a local ASGI client for an already-prepared FastAPI app."""
from basic_memory.workspace_context import workspace_permalink_headers
return AsyncClient(
transport=ASGITransport(app=app),
base_url="http://test",
timeout=timeout,
# Local ASGI calls still cross the HTTP boundary, so request handlers need
# the same workspace permalink metadata that cloud proxy calls receive.
headers=workspace_permalink_headers(),
)
def _get_prepared_local_asgi_database_prepare_lock(app: FastAPI) -> Lock:
"""Get the async lock that serializes first-time DB preparation for an app."""
with _prepared_local_asgi_database_lock:
prepare_lock = _prepared_local_asgi_database_prepare_locks.get(app)
if prepare_lock is None:
prepare_lock = Lock()
_prepared_local_asgi_database_prepare_locks[app] = prepare_lock
return prepare_lock
@asynccontextmanager
async def _resolve_local_asgi_database(app: FastAPI) -> AsyncIterator[LocalDatabaseState]:
"""Resolve database state for a local ASGI request."""
from fastapi.dependencies.utils import get_dependant, solve_dependencies
from basic_memory.deps import get_engine_factory
async def resolve_database_state(
database_state: Annotated[LocalDatabaseState, Depends(get_engine_factory)],
) -> LocalDatabaseState:
return database_state
scope: dict[str, Any] = {
"type": "http",
"asgi": {"version": "3.0"},
"method": "GET",
"scheme": "http",
"path": "/",
"raw_path": b"/",
"root_path": "",
"query_string": b"",
"headers": [],
"client": ("testclient", 50000),
"server": ("testserver", 80),
"app": app,
"path_params": {},
}
async with AsyncExitStack() as request_stack, AsyncExitStack() as function_stack:
scope["fastapi_inner_astack"] = request_stack
scope["fastapi_function_astack"] = function_stack
request = Request(scope)
dependant = get_dependant(path="/", call=resolve_database_state)
solved = await solve_dependencies(
request=request,
dependant=dependant,
dependency_overrides_provider=app,
async_exit_stack=request_stack,
embed_body_fields=False,
)
if solved.errors:
raise RuntimeError(f"Failed to resolve local ASGI database dependency: {solved.errors}")
yield await resolve_database_state(**solved.values)
def _retain_prepared_local_asgi_database(app: FastAPI) -> bool:
"""Retain an active local ASGI database preparation if one exists."""
with _prepared_local_asgi_database_lock:
active = _prepared_local_asgi_databases.get(app)
if active is None:
return False
active.active_count += 1
return True
def _install_prepared_local_asgi_database(
app: FastAPI,
database_state: LocalDatabaseState,
dependency_context: AbstractAsyncContextManager[LocalDatabaseState],
) -> None:
"""Install local ASGI database state after dependency resolution."""
with _prepared_local_asgi_database_lock:
active = _prepared_local_asgi_databases.get(app)
if active is not None:
raise RuntimeError("Local ASGI database state installed while another state is active")
previous_engine = getattr(app.state, "engine", _MISSING_STATE_VALUE)
previous_session_maker = getattr(app.state, "session_maker", _MISSING_STATE_VALUE)
engine, session_maker = database_state
app.state.engine = engine
app.state.session_maker = session_maker
_prepared_local_asgi_databases[app] = _PreparedLocalAsgiDatabase(
active_count=1,
previous_engine=previous_engine,
previous_session_maker=previous_session_maker,
dependency_context=dependency_context,
)
def _restore_local_asgi_state_attribute(app: FastAPI, name: str, previous_value: object) -> None:
"""Restore a FastAPI app.state attribute captured before local ASGI preparation."""
if previous_value is _MISSING_STATE_VALUE:
if hasattr(app.state, name):
delattr(app.state, name)
else:
setattr(app.state, name, previous_value)
def _release_prepared_local_asgi_database(
app: FastAPI,
) -> AbstractAsyncContextManager[LocalDatabaseState] | None:
"""Release local ASGI database state after a client context exits."""
with _prepared_local_asgi_database_lock:
active = _prepared_local_asgi_databases.get(app)
if active is None:
raise RuntimeError("Local ASGI database state released without a matching retain")
active.active_count -= 1
if active.active_count > 0:
return None
del _prepared_local_asgi_databases[app]
_restore_local_asgi_state_attribute(app, "engine", active.previous_engine)
_restore_local_asgi_state_attribute(
app,
"session_maker",
active.previous_session_maker,
)
return active.dependency_context
@asynccontextmanager
async def _prepared_local_asgi_database(app: FastAPI) -> AsyncIterator[None]:
"""Initialize local ASGI database state before the first request."""
prepare_lock = _get_prepared_local_asgi_database_prepare_lock(app)
async with prepare_lock:
if not _retain_prepared_local_asgi_database(app):
database_context = _resolve_local_asgi_database(app)
database_state = await database_context.__aenter__()
try:
_install_prepared_local_asgi_database(app, database_state, database_context)
except Exception:
await database_context.__aexit__(None, None, None)
raise
try:
yield
finally:
database_context = _release_prepared_local_asgi_database(app)
if database_context is not None:
await database_context.__aexit__(None, None, None)
@asynccontextmanager
async def _asgi_client(timeout: Timeout) -> AsyncIterator[AsyncClient]:
def _asgi_client(timeout: Timeout) -> AsyncClient:
"""Create a local ASGI client."""
# Import on first local-client use so CLI help/version paths can import
# routing helpers without constructing the full FastAPI router graph.
from basic_memory.api.app import app as fastapi_app
# Trigger: local ASGITransport does not execute FastAPI lifespan startup.
# Why: letting request dependencies initialize Postgres can run asyncpg DDL
# under Starlette's request loop and trigger CPython's empty-ready-queue race.
# Outcome: request handling sees the same app.state database objects as API
# lifespan startup would have provided.
async with _prepared_local_asgi_database(fastapi_app):
async with _build_asgi_client(fastapi_app, timeout) as client:
yield client
return AsyncClient(
transport=ASGITransport(app=fastapi_app), base_url="http://test", timeout=timeout
)
async def _resolve_cloud_token(config) -> str:
@@ -286,12 +94,9 @@ async def _cloud_client(
workspace: Optional[str] = None,
) -> AsyncIterator[AsyncClient]:
"""Create a cloud proxy client with resolved credentials."""
from basic_memory.workspace_context import workspace_permalink_headers
token = await _resolve_cloud_token(config)
proxy_base_url = f"{config.cloud_host}/proxy"
headers = {"Authorization": f"Bearer {token}"}
headers.update(workspace_permalink_headers())
if workspace:
headers["X-Workspace-ID"] = workspace
logger.info(f"Creating HTTP client for cloud proxy at: {proxy_base_url}")
@@ -443,12 +248,7 @@ def create_client() -> AsyncClient:
if _force_local_mode() or not _force_cloud_mode():
logger.info("Creating ASGI client for local Basic Memory API")
# Deprecated sync path: create_client() cannot await the local ASGI
# pre-initialization used by get_client(), so callers that need proper
# resource setup should use the async context manager instead.
from basic_memory.api.app import app as fastapi_app
return _build_asgi_client(fastapi_app, timeout)
return _asgi_client(timeout)
logger.info("Creating HTTP client for cloud proxy (legacy create_client path)")
config = ConfigManager().config
+10 -4
View File
@@ -15,7 +15,6 @@ from basic_memory.schemas.response import (
DirectoryMoveResult,
DirectoryDeleteResult,
)
from basic_memory.schemas.v2.graph import GraphNode, OrphanEntitiesResponse
class KnowledgeClient:
@@ -278,8 +277,15 @@ class KnowledgeClient:
# --- Orphan detection ---
async def get_orphans(self) -> list[GraphNode]:
"""Get entities that have no incoming or outgoing relations."""
async def get_orphans(self) -> list[dict]:
"""Get entities that have no incoming or outgoing relations.
Returns:
List of entity dicts with external_id, title, note_type, file_path
Raises:
ToolError: If the request fails
"""
with logfire.span(
"mcp.client.knowledge.get_orphans",
client_name="knowledge",
@@ -292,7 +298,7 @@ class KnowledgeClient:
operation="get_orphans",
path_template="/v2/projects/{project_id}/knowledge/orphans",
)
return OrphanEntitiesResponse.model_validate(response.json()).entities
return response.json()["entities"]
# --- Resolution ---
+20 -1
View File
@@ -3,6 +3,8 @@
Encapsulates all /v2/projects/{project_id}/resource/* endpoints.
"""
from typing import Optional
from httpx import AsyncClient, Response
import logfire
@@ -37,11 +39,19 @@ class ResourceClient:
self.project_id = project_id
self._base_path = f"/v2/projects/{project_id}/resource"
async def read(self, entity_id: str) -> Response:
async def read(
self,
entity_id: str,
*,
page: Optional[int] = None,
page_size: Optional[int] = None,
) -> Response:
"""Read a resource by entity ID.
Args:
entity_id: Entity external_id (UUID)
page: Optional page number for paginated content
page_size: Optional page size for paginated content
Returns:
Raw HTTP Response (caller handles text/binary content)
@@ -49,14 +59,23 @@ class ResourceClient:
Raises:
ToolError: If the resource is not found or request fails
"""
params: dict = {}
if page is not None:
params["page"] = page
if page_size is not None:
params["page_size"] = page_size
with logfire.span(
"mcp.client.resource.read",
client_name="resource",
operation="read",
page=page,
page_size=page_size,
):
return await call_get(
self.http_client,
f"{self._base_path}/{entity_id}",
params=params if params else None,
client_name="resource",
operation="read",
path_template="/v2/projects/{project_id}/resource/{entity_id}",
+103 -600
View File
@@ -9,10 +9,9 @@ compatibility with existing MCP tools.
"""
import asyncio
from contextlib import asynccontextmanager, nullcontext
from dataclasses import dataclass, field
from typing import AsyncIterator, Awaitable, Callable, List, Optional, Sequence, Tuple, cast
from uuid import UUID
from contextlib import asynccontextmanager
from dataclasses import dataclass
from typing import AsyncIterator, Awaitable, Callable, Optional, List, Tuple, cast
from httpx import AsyncClient
from httpx._types import (
@@ -25,26 +24,11 @@ from mcp.server.fastmcp.exceptions import ToolError
import logfire
from basic_memory.config import BasicMemoryConfig, ConfigManager, ProjectMode, has_cloud_credentials
from basic_memory.project_resolver import ProjectResolver
from basic_memory.schemas.cloud import (
WorkspaceInfo,
WorkspaceListResponse,
format_workspace_choices,
format_workspace_selection_choices,
workspace_matches_exact_identifier,
workspace_matches_identifier,
)
from basic_memory.schemas.cloud import WorkspaceInfo, WorkspaceListResponse
from basic_memory.schemas.project_info import ProjectItem, ProjectList
from basic_memory.schemas.v2 import ProjectResolveResponse
from basic_memory.schemas.memory import memory_url_path
from basic_memory.utils import (
build_qualified_permalink_reference,
generate_permalink,
normalize_project_reference,
)
from basic_memory.workspace_context import (
current_workspace_permalink_context,
workspace_permalink_context,
)
from basic_memory.utils import generate_permalink, normalize_project_reference
# --- Workspace provider injection ---
# Mirrors the set_client_factory() pattern in async_client.py.
@@ -68,27 +52,14 @@ class WorkspaceProjectEntry:
@dataclass(frozen=True)
class WorkspaceProjectIndex:
"""Session-local cloud project lookup index keyed by project permalink and external_id."""
"""Session-local cloud project lookup index keyed by project permalink."""
workspaces: tuple[WorkspaceInfo, ...]
entries: tuple[WorkspaceProjectEntry, ...]
entries_by_permalink: dict[str, tuple[WorkspaceProjectEntry, ...]]
entries_by_external_id: dict[str, WorkspaceProjectEntry] = field(default_factory=dict)
failed_workspaces: tuple[WorkspaceInfo, ...] = ()
@dataclass(frozen=True)
class WorkspaceMemoryUrlResolution:
"""Resolved workspace/project route for a workspace-qualified memory URL."""
entry: WorkspaceProjectEntry
canonical_path: str
@property
def project_identifier(self) -> str:
return self.entry.qualified_name
def set_workspace_provider(provider: Callable[[], Awaitable[list[WorkspaceInfo]]]) -> None:
"""Override workspace discovery (for cloud app, testing, etc)."""
global _workspace_provider
@@ -142,15 +113,6 @@ async def _set_cached_active_project(
await context.set_state("default_project_name", active_project.name)
async def _clear_cached_active_project(context: Optional[Context]) -> None:
"""Clear cached project metadata that may no longer match the active route."""
if not context:
return
await context.set_state("active_project", None)
await context.set_state("default_project_name", None)
async def _get_cached_active_workspace(context: Optional[Context]) -> Optional[WorkspaceInfo]:
"""Return the cached active workspace from context when available."""
if not context:
@@ -176,22 +138,12 @@ async def _set_cached_active_workspace(
# Why: project names are only unique inside one workspace, so a cached
# ProjectItem from the previous tenant can point at the wrong project
# Outcome: force the next validation call to resolve within the new tenant
await _clear_cached_active_project(context)
await context.set_state("active_project", None)
await context.set_state("default_project_name", None)
await context.set_state("active_workspace", active_workspace.model_dump())
async def _clear_cached_active_workspace_for_local_route(context: Optional[Context]) -> None:
"""Drop tenant workspace metadata before routing through a local project."""
if not context:
return
# Trigger: local routing follows a cloud route in the same MCP session
# Why: active_workspace is tenant metadata, not part of local project identity
# Outcome: memory:// resolution uses project-only local permalinks
await context.set_state("active_workspace", None)
async def _get_cached_default_project(context: Optional[Context]) -> Optional[str]:
"""Return the cached default project name from context when available."""
if not context:
@@ -314,6 +266,29 @@ async def get_project_names(client: AsyncClient, headers: HeaderTypes | None = N
return [project.name for project in project_list.projects]
def _workspace_matches_identifier(workspace: WorkspaceInfo, identifier: str) -> bool:
"""Return True when identifier matches workspace tenant_id, slug, or name."""
if workspace.tenant_id == identifier:
return True
if workspace.slug.casefold() == identifier.casefold():
return True
return workspace.name.lower() == identifier.lower()
def _workspace_choices(workspaces: list[WorkspaceInfo]) -> str:
"""Format deterministic workspace choices for prompt-style errors."""
return "\n".join(
[
(
f"- {item.name} "
f"(slug={item.slug}, type={item.workspace_type}, "
f"role={item.role}, tenant_id={item.tenant_id})"
)
for item in workspaces
]
)
def _workspace_project_index_from_state(raw: object) -> WorkspaceProjectIndex | None:
"""Deserialize a cached workspace project index from MCP context state."""
if not isinstance(raw, dict):
@@ -376,12 +351,10 @@ def _build_workspace_project_index(
*,
failed_workspaces: tuple[WorkspaceInfo, ...] = (),
) -> WorkspaceProjectIndex:
"""Build the permalink and external_id lookup tables for workspace-project entries."""
"""Build the permalink lookup table for workspace-project entries."""
grouped: dict[str, list[WorkspaceProjectEntry]] = {}
by_external_id: dict[str, WorkspaceProjectEntry] = {}
for entry in entries:
grouped.setdefault(entry.project.permalink, []).append(entry)
by_external_id[entry.project.external_id] = entry
return WorkspaceProjectIndex(
workspaces=workspaces,
@@ -390,7 +363,6 @@ def _build_workspace_project_index(
permalink: tuple(items)
for permalink, items in sorted(grouped.items(), key=lambda item: item[0])
},
entries_by_external_id=by_external_id,
failed_workspaces=failed_workspaces,
)
@@ -413,232 +385,7 @@ def _unqualified_project_identifier(identifier: str) -> str:
return project_identifier
def _identifier_path(identifier: str) -> str:
"""Return the routable path portion of a raw identifier or memory URL."""
stripped = identifier.strip()
return memory_url_path(stripped) if stripped.startswith("memory://") else stripped
def _split_workspace_identifier_segments(identifier: str) -> tuple[str, str, str] | None:
"""Split ``<workspace>/<project>/<path>`` identifiers into route segments."""
normalized = normalize_project_reference(_identifier_path(identifier)).strip("/")
parts = normalized.split("/", 2)
if len(parts) != 3:
# Trigger: two-segment identifiers such as `workspace/project` or `project/path`.
# Why: without a remainder, the shape is ambiguous with existing project-prefix routing.
# Outcome: fall through so the normal project-prefix/default-project resolver decides.
return None
workspace_slug, project_identifier, remainder = parts
if not workspace_slug or not project_identifier or not remainder:
return None
return workspace_slug, project_identifier, remainder
def _split_workspace_memory_url_segments(identifier: str) -> tuple[str, str, str] | None:
"""Split ``memory://<workspace>/<project>/<path>`` into route segments."""
if not identifier.strip().startswith("memory://"):
return None
return _split_workspace_identifier_segments(identifier)
def _canonical_memory_path_for_workspace(
*,
workspace_slug: str,
workspace_type: str,
project_permalink: str,
remainder: str,
) -> str:
"""Return the stored canonical path for a workspace-qualified memory URL."""
normalized_remainder = remainder.strip("/")
if workspace_type not in {"organization", "personal"}:
raise ValueError(f"Unsupported workspace_type for memory URL routing: {workspace_type}")
# Trigger: a caller supplied a workspace-qualified memory URL.
# Why: the first two path segments are the global route, even for Personal.
# Outcome: lookups preserve the complete workspace/project canonical permalink.
if not normalized_remainder:
normalized_remainder = project_permalink
return build_qualified_permalink_reference(
project_permalink,
normalized_remainder,
include_project=True,
workspace_permalink=workspace_slug,
)
def _canonical_memory_path_for_active_route(
active_project: ProjectItem,
path: str,
*,
include_project: bool,
cached_workspace: WorkspaceInfo | None = None,
) -> str:
"""Return the canonical permalink path for the currently routed project/workspace."""
project_prefix = active_project.permalink
workspace_remainder = path
if include_project and (path == project_prefix or path.startswith(f"{project_prefix}/")):
# Trigger: the memory URL already names the active project root/prefix
# Why: workspace canonicalization adds the project prefix itself, so
# keeping it in the remainder would produce <workspace>/<project>/<project>
# Outcome: keep project-root and project-prefixed URLs canonical once
workspace_remainder = (
"" if path == project_prefix else path.removeprefix(f"{project_prefix}/")
)
workspace_context = current_workspace_permalink_context()
if workspace_context is not None:
return _canonical_memory_path_for_workspace(
workspace_slug=workspace_context.workspace_slug,
workspace_type=workspace_context.workspace_type,
project_permalink=active_project.permalink,
remainder=workspace_remainder,
)
if cached_workspace is not None:
return _canonical_memory_path_for_workspace(
workspace_slug=cached_workspace.slug,
workspace_type=cached_workspace.workspace_type,
project_permalink=active_project.permalink,
remainder=workspace_remainder,
)
if not include_project:
return path
if path == project_prefix or path.startswith(f"{project_prefix}/"):
return path
return f"{project_prefix}/{path}"
def _cloud_workspace_discovery_available(config: BasicMemoryConfig) -> bool:
"""Return True when workspace discovery can be used without forcing local routing."""
from basic_memory.mcp.async_client import (
_explicit_routing,
_force_local_mode,
is_factory_mode,
)
if _explicit_routing() and _force_local_mode():
return False
# Trigger: local project config is present even though cloud credentials are saved.
# Why: existing local `memory://...` URLs must not depend on workspace discovery.
# Outcome: only factory, explicit cloud, or cloud-only sessions attempt discovery here.
return (
is_factory_mode()
or (_explicit_routing() and not _force_local_mode())
or (not config.projects and has_cloud_credentials(config))
)
def _workspace_identifier_discovery_available(
identifier: str,
config: BasicMemoryConfig,
) -> bool:
"""Return True when an identifier is allowed to consult workspace discovery."""
if _cloud_workspace_discovery_available(config):
return True
from basic_memory.mcp.async_client import (
_explicit_routing,
_force_local_mode,
)
if _explicit_routing() and _force_local_mode():
return False
return (
has_cloud_credentials(config)
and _split_workspace_identifier_segments(identifier) is not None
)
async def resolve_workspace_qualified_memory_url(
identifier: str,
context: Optional[Context] = None,
) -> WorkspaceMemoryUrlResolution | None:
"""Resolve a workspace-qualified memory URL against accessible workspaces."""
segments = _split_workspace_memory_url_segments(identifier)
if segments is None:
return None
return await _resolve_workspace_segments(identifier, segments, context=context)
async def resolve_workspace_qualified_identifier(
identifier: str,
context: Optional[Context] = None,
) -> WorkspaceMemoryUrlResolution | None:
"""Resolve a workspace-qualified permalink or memory URL against accessible workspaces."""
segments = _split_workspace_identifier_segments(identifier)
if segments is None:
return None
return await _resolve_workspace_segments(identifier, segments, context=context)
async def _resolve_workspace_segments(
identifier: str,
segments: tuple[str, str, str],
context: Optional[Context] = None,
) -> WorkspaceMemoryUrlResolution | None:
"""Resolve parsed workspace/project/path segments against accessible workspaces."""
workspace_slug, project_identifier, remainder = segments
index = await _ensure_workspace_project_index(context=context)
workspace = next(
(item for item in index.workspaces if item.slug.casefold() == workspace_slug.casefold()),
None,
)
if workspace is None:
return None
project_permalink = generate_permalink(project_identifier)
matches = [
entry
for entry in index.entries_by_permalink.get(project_permalink, ())
if entry.workspace.tenant_id == workspace.tenant_id
]
if not matches:
if any(
failed_workspace.tenant_id == workspace.tenant_id
for failed_workspace in index.failed_workspaces
):
raise ValueError(
f"Projects for workspace '{workspace.name}' ({workspace.slug}) "
"could not be loaded. Retry after workspace discovery recovers."
)
# Trigger: first segment matches a workspace slug but the second does not
# match a project in that workspace.
# Why: workspace-qualified URLs require both route segments to match; otherwise
# existing project-prefixed URLs like `memory://main/notes/foo` can collide
# with a workspace slug named `main`.
# Outcome: treat this as not workspace-qualified and let the caller use
# the existing project-prefix/default-project resolver.
return None
if len(matches) > 1:
details = ", ".join(
f"{entry.qualified_name} ({entry.project.external_id})" for entry in matches
)
raise ValueError(
f"Project '{project_identifier}' matched multiple projects in workspace "
f"'{workspace.name}' ({workspace.slug}). Project permalinks must be unique. "
f"Matches: {details}"
)
entry = matches[0]
canonical_path = _canonical_memory_path_for_workspace(
workspace_slug=entry.workspace.slug,
workspace_type=entry.workspace.workspace_type,
project_permalink=entry.project.permalink,
remainder=remainder,
)
return WorkspaceMemoryUrlResolution(entry=entry, canonical_path=canonical_path)
def _format_qualified_choices(entries: Sequence[WorkspaceProjectEntry]) -> str:
def _format_qualified_choices(entries: tuple[WorkspaceProjectEntry, ...]) -> str:
"""Format qualified project choices for collision errors."""
return " or ".join(entry.qualified_name for entry in entries)
@@ -764,7 +511,7 @@ async def _ensure_workspace_project_index(
)
continue
workspace_entries = result
workspace_entries = cast(tuple[WorkspaceProjectEntry, ...], result)
successful_fetches += 1
entries_list.extend(workspace_entries)
@@ -802,20 +549,8 @@ async def resolve_workspace_project_identifier(
project: str,
context: Optional[Context] = None,
) -> WorkspaceProjectEntry:
"""Resolve a project by external_id (UUID), qualified name, or unqualified name."""
"""Resolve an unqualified or ``<workspace>/<project>`` cloud project identifier."""
index = await _ensure_workspace_project_index(context=context)
# Fast path: direct lookup by external_id when the identifier is a UUID
# Canonicalize via str(UUID(...)) so uppercase, brace-wrapped, or urn:uuid forms
# all hash to the same lowercase-hyphenated key as the stored external_ids.
try:
canonical_external_id = str(UUID(project))
entry = index.entries_by_external_id.get(canonical_external_id)
if entry:
return entry
except ValueError:
pass
workspace_slug, project_identifier = _split_qualified_project_identifier(project)
project_permalink = generate_permalink(project_identifier)
@@ -856,18 +591,9 @@ async def resolve_workspace_project_identifier(
f"Project '{project_identifier}' was not found in workspace "
f"'{workspace.name}' ({workspace.slug}). Available projects: {available}"
)
if len(matches) > 1:
details = ", ".join(
f"{entry.qualified_name} ({entry.project.external_id})" for entry in matches
)
raise ValueError(
f"Project '{project_identifier}' matched multiple projects in workspace "
f"'{workspace.name}' ({workspace.slug}). Project permalinks must be unique. "
f"Matches: {details}"
)
return matches[0]
matches = list(index.entries_by_permalink.get(project_permalink, ()))
matches = index.entries_by_permalink.get(project_permalink, ())
if not matches:
failed_note = ""
if index.failed_workspaces:
@@ -891,11 +617,6 @@ async def resolve_workspace_project_identifier(
return cached_matches[0]
if len(matches) > 1:
# Prefer the project in the default workspace when name is ambiguous
default_match = next((entry for entry in matches if entry.workspace.is_default), None)
if default_match:
return default_match
choices = _format_qualified_choices(matches)
details = "\n".join(
f"- {entry.workspace.name} ({entry.workspace.slug}): {entry.qualified_name}"
@@ -937,56 +658,6 @@ async def _default_workspace_project_entry(
return default_entries[0] if default_entries else None
async def _workspace_metadata_by_tenant_id(
tenant_id: str,
context: Optional[Context] = None,
) -> WorkspaceInfo | None:
"""Return non-index workspace metadata for a configured tenant id."""
cached_workspace = await _get_cached_active_workspace(context)
if cached_workspace and cached_workspace.tenant_id == tenant_id:
return cached_workspace
if cached_workspace and context:
# Trigger: the configured workspace_id differs from cached workspace metadata.
# Why: tenant_id routes the request, but stale workspace slug/type would corrupt
# memory URL normalization and canonical permalink headers.
# Outcome: drop stale metadata and route without permalink decoration.
await context.set_state("active_workspace", None)
if context:
cached_raw = await context.get_state("available_workspaces")
if isinstance(cached_raw, list):
for item in cached_raw:
if not isinstance(item, dict):
continue
workspace = WorkspaceInfo.model_validate(item)
if workspace.tenant_id == tenant_id:
return workspace
if _workspace_provider is not None:
# Trigger: the hosting runtime can provide workspace metadata directly.
# Why: configured workspace_id is already sufficient for tenant routing, but
# canonical organization permalinks also need slug/type context.
# Outcome: use the injected runtime seam without loading the workspace project index.
workspace = next(
(
workspace
for workspace in await get_available_workspaces(context=context)
if workspace.tenant_id == tenant_id
),
None,
)
if workspace is None:
raise ValueError(
f"Configured workspace_id '{tenant_id}' was not returned by the workspace "
"metadata provider. Reconfigure the project workspace or retry after "
"workspace metadata recovers."
)
return workspace
return None
async def resolve_workspace_parameter(
workspace: Optional[str] = None,
context: Optional[Context] = None,
@@ -1001,9 +672,7 @@ async def resolve_workspace_parameter(
cached_raw = await context.get_state("active_workspace")
if isinstance(cached_raw, dict):
cached_workspace = WorkspaceInfo.model_validate(cached_raw)
if workspace is None or workspace_matches_exact_identifier(
cached_workspace, workspace
):
if workspace is None or _workspace_matches_identifier(cached_workspace, workspace):
logger.debug(
f"Using cached workspace from context: {cached_workspace.tenant_id}"
)
@@ -1019,17 +688,19 @@ async def resolve_workspace_parameter(
selected_workspace: WorkspaceInfo | None = None
if workspace:
matches = [item for item in workspaces if workspace_matches_identifier(item, workspace)]
matches = [
item for item in workspaces if _workspace_matches_identifier(item, workspace)
]
if not matches:
raise ValueError(
f"Workspace '{workspace}' was not found.\n"
f"Available workspaces:\n{format_workspace_choices(workspaces)}"
f"Available workspaces:\n{_workspace_choices(workspaces)}"
)
if len(matches) > 1:
raise ValueError(
f"Workspace '{workspace}' matches multiple workspaces. "
"Choose one of these matching workspaces by slug or tenant_id:\n"
f"{format_workspace_selection_choices(matches)}"
f"Workspace name '{workspace}' matches multiple workspaces. "
"Use tenant_id instead.\n"
f"Available workspaces:\n{_workspace_choices(workspaces)}"
)
selected_workspace = matches[0]
elif len(workspaces) == 1:
@@ -1037,8 +708,8 @@ async def resolve_workspace_parameter(
else:
raise ValueError(
"Multiple workspaces are available. Ask the user which workspace to use, then retry "
"with the 'workspace' argument set to the tenant_id or unique name/slug/type.\n"
f"Available workspaces:\n{format_workspace_choices(workspaces)}"
"with the 'workspace' argument set to the tenant_id or unique name.\n"
f"Available workspaces:\n{_workspace_choices(workspaces)}"
)
await _set_cached_active_workspace(context, selected_workspace)
@@ -1163,55 +834,13 @@ async def resolve_project_and_path(
return active_project, identifier, False
normalized_path = normalize_project_reference(memory_url_path(identifier))
cached_project = await _get_cached_active_project(context)
cached_workspace = await _get_cached_active_workspace(context)
if cached_project and cached_workspace:
workspace_prefix = generate_permalink(cached_workspace.slug)
qualified_prefix = f"{workspace_prefix}/{cached_project.permalink}"
if normalized_path == qualified_prefix or normalized_path.startswith(
f"{qualified_prefix}/"
):
remainder = (
""
if normalized_path == qualified_prefix
else normalized_path.removeprefix(f"{qualified_prefix}/")
)
resolved_path = _canonical_memory_path_for_workspace(
workspace_slug=cached_workspace.slug,
workspace_type=cached_workspace.workspace_type,
project_permalink=cached_project.permalink,
remainder=remainder,
)
return cached_project, resolved_path, True
workspace_context = current_workspace_permalink_context()
if workspace_context and project:
workspace_prefix = generate_permalink(workspace_context.workspace_slug)
project_permalink = generate_permalink(_unqualified_project_identifier(project))
qualified_prefix = f"{workspace_prefix}/{project_permalink}"
if normalized_path == qualified_prefix or normalized_path.startswith(
f"{qualified_prefix}/"
):
active_project = await get_active_project(client, project, context, headers)
remainder = (
""
if normalized_path == qualified_prefix
else normalized_path.removeprefix(f"{qualified_prefix}/")
)
resolved_path = _canonical_memory_path_for_workspace(
workspace_slug=workspace_context.workspace_slug,
workspace_type=workspace_context.workspace_type,
project_permalink=project_permalink,
remainder=remainder,
)
return active_project, resolved_path, True
project_prefix, remainder = _split_project_prefix(normalized_path)
include_project = config.permalinks_include_project
# Trigger: memory URL begins with a potential project segment
# Why: allow project-scoped memory URLs without requiring a separate project parameter
# Outcome: attempt to resolve the prefix as a project and route to it
if project_prefix:
cached_project = await _get_cached_active_project(context)
if cached_project and _project_matches_identifier(cached_project, project_prefix):
resolved_project = await resolve_project_parameter(project_prefix, context=context)
if resolved_project and generate_permalink(resolved_project) != generate_permalink(
@@ -1221,11 +850,8 @@ async def resolve_project_and_path(
f"Project is constrained to '{resolved_project}', cannot use '{project_prefix}'."
)
resolved_path = _canonical_memory_path_for_active_route(
cached_project,
remainder,
include_project=include_project,
cached_workspace=cached_workspace,
resolved_path = (
f"{cached_project.permalink}/{remainder}" if include_project else remainder
)
return cached_project, resolved_path, True
@@ -1260,24 +886,25 @@ async def resolve_project_and_path(
)
await _set_cached_active_project(context, active_project)
resolved_path = _canonical_memory_path_for_active_route(
active_project,
remainder,
include_project=include_project,
cached_workspace=cached_workspace,
resolved_path = (
f"{resolved.permalink}/{remainder}" if include_project else remainder
)
return active_project, resolved_path, True
# Trigger: memory URL has no resolvable project route segment
# Why: preserve active-project behavior while honoring workspace paths
# Outcome: normalize against the already-selected local/cloud route
# Trigger: no resolvable project prefix in the memory URL
# Why: preserve existing memory URL behavior within the active project
# Outcome: use the active project and normalize the path for lookup
active_project = await get_active_project(client, project, context, headers)
resolved_path = _canonical_memory_path_for_active_route(
active_project,
normalized_path,
include_project=include_project,
cached_workspace=cached_workspace,
)
resolved_path = normalized_path
if include_project:
# Trigger: project-prefixed permalinks are enabled and the path lacks a prefix
# Why: ensure memory URL lookups align with canonical permalinks
# Outcome: prefix the path with the active project's permalink
project_prefix = active_project.permalink
if resolved_path != project_prefix and not resolved_path.startswith(
f"{project_prefix}/"
):
resolved_path = f"{project_prefix}/{resolved_path}"
return active_project, resolved_path, True
@@ -1326,81 +953,11 @@ def detect_project_from_url_prefix(identifier: str, config: BasicMemoryConfig) -
return None
async def detect_project_from_memory_url_prefix(
identifier: str,
config: BasicMemoryConfig,
context: Optional[Context] = None,
) -> Optional[str]:
"""Resolve a project from a memory URL prefix, including workspace-qualified URLs."""
if not identifier.strip().startswith("memory://"):
return None
return await detect_project_from_identifier_prefix(identifier, config, context=context)
async def detect_project_from_identifier_prefix(
identifier: str,
config: BasicMemoryConfig,
context: Optional[Context] = None,
) -> Optional[str]:
"""Resolve a project from a plain permalink, memory URL, or workspace route prefix."""
local_project = detect_project_from_url_prefix(identifier, config)
if local_project is not None:
return local_project
normalized_identifier = normalize_project_reference(_identifier_path(identifier)).strip("/")
if "/" not in normalized_identifier:
# Trigger: plain text search query or single-segment title/permalink.
# Why: cloud project discovery can build a workspace index; only path-shaped
# identifiers carry enough structure to justify that cost.
# Outcome: keep unqualified search/title input on the active/default project route.
return None
if _workspace_identifier_discovery_available(identifier, config):
workspace_discovery_fallback_errors = (
"not found",
"no accessible workspaces",
"unable to discover",
)
try:
workspace_resolution = await resolve_workspace_qualified_identifier(
identifier,
context=context,
)
except ValueError as exc:
message = str(exc).lower()
if any(error in message for error in workspace_discovery_fallback_errors):
return None
raise
if workspace_resolution is not None:
return workspace_resolution.project_identifier
project_prefix, _ = _split_project_prefix(normalized_identifier)
if project_prefix is None:
return None
try:
project_resolution = await resolve_workspace_project_identifier(
project_prefix,
context=context,
)
except ValueError as exc:
message = str(exc).lower()
if any(error in message for error in workspace_discovery_fallback_errors):
return None
raise
return project_resolution.qualified_name
return None
@asynccontextmanager
async def get_project_client(
project: Optional[str] = None,
workspace: Optional[str] = None,
context: Optional[Context] = None,
project_id: Optional[str] = None,
) -> AsyncIterator[Tuple[AsyncClient, ProjectItem]]:
"""Resolve project, create correctly-routed client, and validate project.
@@ -1415,13 +972,16 @@ async def get_project_client(
3. Cloud project mode → resolve project through workspace/project index
4. Otherwise → local ASGI client
Workspace resolution priority (when cloud routing):
1. Explicit ``workspace`` parameter
2. Per-project ``workspace_id`` from config
3. Qualified project identifier (``<workspace-slug>/<project>``)
4. Workspace/project index lookup with collision detection
Args:
project: Optional explicit project parameter (name or permalink)
project: Optional explicit project parameter
workspace: Optional cloud workspace selector (tenant_id or unique name)
context: Optional FastMCP context for caching
project_id: Optional project external_id (UUID). When provided, takes
precedence over ``project`` and disambiguates the project across
workspaces. Use this when the same project name exists in multiple
cloud workspaces.
Yields:
Tuple of (client, active_project)
@@ -1438,12 +998,8 @@ async def get_project_client(
is_factory_mode,
)
# When project_id (UUID) is provided, prefer it as the resolution identifier.
# external_id is unambiguous across workspaces; project name can collide.
project_identifier = project_id if project_id else project
# Step 1: Resolve project name from config (no network call)
resolved_project = await resolve_project_parameter(project_identifier, context=context)
resolved_project = await resolve_project_parameter(project, context=context)
config = ConfigManager().config
factory_mode = is_factory_mode()
explicit_cloud_routing = _explicit_routing() and not _force_local_mode()
@@ -1479,7 +1035,6 @@ async def get_project_client(
# Outcome: route strictly based on explicit flag, no workspace network calls
if _explicit_routing() and _force_local_mode():
route_mode = "explicit_local"
await _clear_cached_active_workspace_for_local_route(context)
with logfire.span(
"routing.client_session",
project_name=resolved_project,
@@ -1495,70 +1050,38 @@ async def get_project_client(
project_entry = config.projects.get(resolved_project)
project_mode = config.get_project_mode(resolved_project)
# Trigger: identifier is a UUID (project_id) but local config keys by name only
# Why: get_project_mode defaults to CLOUD for unknown identifiers; a UUID is
# never registered in local config, so it would always falsely route cloud
# Outcome: in pure local mode, treat UUID identifiers as local routing; cloud
# discovery still happens when factory/explicit/credentials are present
cloud_available = factory_mode or explicit_cloud_routing or has_cloud_credentials(config)
if project_id and not cloud_available:
project_mode = ProjectMode.LOCAL
# Trigger: project_id is a local external_id in a mixed local+cloud setup.
# Why: UUIDs are not local config keys, so get_project_mode() treats them as
# cloud projects. A local-first probe avoids making local UUIDs depend on
# healthy cloud workspace discovery.
# Outcome: resolve the effective UUID against local ASGI first; if it is not
# local, preserve the existing cloud workspace lookup path.
# Trigger: workspace provided for a local project (without explicit --cloud)
# Why: workspace selection is a cloud routing concern only
# Outcome: fail fast with a deterministic guidance message
if (
project_id
and config.projects
and not factory_mode
and not explicit_cloud_routing
and project_mode == ProjectMode.CLOUD
not factory_mode
and project_mode != ProjectMode.CLOUD
and workspace is not None
and not _explicit_routing()
):
try:
canonical_project_id = str(UUID(resolved_project))
except ValueError:
pass
else:
with logfire.span(
"routing.local_project_id_probe",
project_id=canonical_project_id,
):
async with get_client() as client:
try:
active_project = await get_active_project(
client,
canonical_project_id,
context,
)
except ToolError as exc:
if "not found" not in str(exc).lower():
raise
else:
route_mode = "local_asgi"
await _clear_cached_active_workspace_for_local_route(context)
with logfire.span(
"routing.client_session",
project_name=active_project.name,
route_mode=route_mode,
):
logger.debug("Using local ASGI routing for project_id")
yield client, active_project
return
raise ValueError(
f"Workspace '{workspace}' cannot be used with local project '{resolved_project}'. "
"Workspace selection is only supported for cloud-mode projects."
)
if factory_mode or project_mode == ProjectMode.CLOUD or explicit_cloud_routing:
route_mode = "factory" if factory_mode else "cloud_proxy"
active_ws: WorkspaceInfo | None = None
resolved_entry: WorkspaceProjectEntry | None = None
workspace_id: str
project_for_api = _unqualified_project_identifier(resolved_project)
if project_entry and project_entry.workspace_id:
# Per-project config stores the cloud tenant id directly
# Trigger: a script or config entry pins the tenant explicitly
# Why: explicit tenant configuration remains the escape hatch during migration
# Outcome: route to that workspace, but validate the project name inside it
if workspace is not None:
active_ws = await resolve_workspace_parameter(workspace=workspace, context=context)
workspace_id = active_ws.tenant_id
elif project_entry and project_entry.workspace_id:
# Trigger: the local project config already stores the cloud tenant id.
# Why: routing can send that id directly; requiring workspace discovery here
# would turn a control-plane listing outage into a project routing failure.
# Outcome: preserve project-scoped routing even when discovery is unavailable.
workspace_id = project_entry.workspace_id
active_ws = await _workspace_metadata_by_tenant_id(workspace_id, context=context)
else:
resolved_entry = cloud_default_entry
if resolved_entry is None or not _project_matches_identifier(
@@ -1574,13 +1097,6 @@ async def get_project_client(
if active_ws is not None:
await _set_cached_active_workspace(context, active_ws)
if resolved_entry is not None:
cached_project = await _get_cached_active_project(context)
if (
cached_project is not None
and cached_project.external_id != resolved_entry.project.external_id
):
await _clear_cached_active_project(context)
with logfire.span(
"routing.client_session",
project_name=project_for_api,
@@ -1588,35 +1104,22 @@ async def get_project_client(
workspace_id=workspace_id,
):
logger.debug("Using resolved workspace for cloud project routing")
permalink_context = (
workspace_permalink_context(active_ws.slug, active_ws.workspace_type)
if active_ws is not None
else nullcontext()
)
with permalink_context:
async with get_client(
project_name=project_for_api,
workspace=workspace_id,
) as client:
active_project = await get_active_project(client, project_for_api, context)
yield client, active_project
async with get_client(
project_name=project_for_api,
workspace=workspace_id,
) as client:
active_project = await get_active_project(client, project_for_api, context)
yield client, active_project
return
# Step 4: Local routing (default)
route_mode = "local_asgi"
await _clear_cached_active_workspace_for_local_route(context)
with logfire.span(
"routing.client_session",
project_name=resolved_project,
route_mode=route_mode,
):
logger.debug("Using default local ASGI routing for project client")
# Trigger: UUID identifiers won't match name-keyed local config entries.
# Why: get_client(project_name=<uuid>) would consult get_project_mode and
# default to CLOUD for unknown identifiers, breaking pure-local routing.
# Outcome: skip per-project routing for UUIDs — local mode routes every
# project through the same ASGI client; the API resolves the UUID below.
client_kwargs = {} if project_id else {"project_name": resolved_project}
async with get_client(**client_kwargs) as client:
async with get_client(project_name=resolved_project) as client:
active_project = await get_active_project(client, resolved_project, context)
yield client, active_project
@@ -18,15 +18,13 @@ Basic Memory creates a semantic knowledge graph from markdown files. Focus on bu
**Resolution priority:**
1. CLI constraint: `BASIC_MEMORY_MCP_PROJECT` env var (highest priority)
2. Explicit parameter: `project_id="<uuid>"` (preferred when known) or `project="name"` in tool calls
2. Explicit parameter: `project="name"` in tool calls
3. Default project: `default_project` in config (fallback)
**`project` vs `project_id`:** Every project has a stable `external_id` (UUID) returned by `list_memory_projects()`. Pass it as `project_id=...` to address a project unambiguously — required when the same project name exists in multiple cloud workspaces. For local single-project setups, the `project` name is fine.
### Quick Setup Check
```python
# Discover projects (each entry includes external_id you can pass as project_id)
# Discover projects
projects = await list_memory_projects()
```
@@ -171,14 +169,6 @@ await write_note(
**Multi-project users:**
- Always specify project explicitly in tool calls
**Cloud multi-workspace users:** project names can collide across workspaces. After calling `list_memory_projects()`, prefer the project's `external_id` via `project_id=...` for any subsequent tool calls — it routes to the exact project regardless of name collisions. The `project` name parameter falls back to the default workspace on ambiguity, which may not be what you want.
```python
# Cloud / multi-workspace: prefer project_id (UUID) once you've discovered it
projects = await list_memory_projects()
results = await search_notes(query="auth", project_id=projects[0]["external_id"])
```
**Discovery:**
```python
# Start with discovery
+13 -45
View File
@@ -1,15 +1,14 @@
"""Build context tool for Basic Memory MCP server."""
from typing import Annotated, Optional, Literal
from typing import Optional, Literal
import logfire
from loguru import logger
from fastmcp import Context
from pydantic import AliasChoices, Field
from basic_memory.config import ConfigManager
from basic_memory.mcp.project_context import (
detect_project_from_memory_url_prefix,
detect_project_from_url_prefix,
get_project_client,
resolve_project_and_path,
)
@@ -134,34 +133,14 @@ def _format_context_markdown(graph: GraphContext, project: str) -> str:
annotations={"readOnlyHint": True, "openWorldHint": False},
)
async def build_context(
url: Annotated[
MemoryUrl,
Field(validation_alias=AliasChoices("url", "uri", "memory_url")),
],
url: MemoryUrl,
project: Optional[str] = None,
project_id: Optional[str] = None,
workspace: Optional[str] = None,
depth: str | int | None = 1,
timeframe: Annotated[
Optional[TimeFrame],
Field(
default="7d",
validation_alias=AliasChoices("timeframe", "since", "time_range", "lookback"),
),
] = "7d",
# `offset` is intentionally NOT aliased: it has different semantics
# (item-indexed vs. 1-indexed page-number).
page: Annotated[
int,
Field(default=1, validation_alias=AliasChoices("page", "page_number")),
] = 1,
page_size: Annotated[
int,
Field(default=10, validation_alias=AliasChoices("page_size", "limit", "per_page")),
] = 10,
max_related: Annotated[
int,
Field(default=10, validation_alias=AliasChoices("max_related", "max_results")),
] = 10,
timeframe: Optional[TimeFrame] = "7d",
page: int = 1,
page_size: int = 10,
max_related: int = 10,
output_format: Literal["json", "text"] = "json",
context: Context | None = None,
) -> dict | str:
@@ -179,9 +158,6 @@ async def build_context(
Args:
project: Project name to build context from. Optional - server will resolve using hierarchy.
If unknown, use list_memory_projects() to discover available projects.
project_id: Project external_id (UUID). Prefer this over `project` when known —
it routes to the exact project regardless of name collisions across cloud
workspaces. Takes precedence over `project`. Get from list_memory_projects().
url: memory:// URI pointing to discussion content (e.g. memory://specs/search)
depth: How many relation hops to traverse (1-3 recommended for performance)
timeframe: How far back to look. Supports natural language like "2 days ago", "last week"
@@ -209,14 +185,9 @@ async def build_context(
Raises:
ToolError: If project doesn't exist or depth parameter is invalid
"""
# Detect project from memory URL prefix before routing.
# project_id routes by external UUID, so it bypasses URL discovery entirely.
if project is None and project_id is None:
detected = await detect_project_from_memory_url_prefix(
url,
ConfigManager().config,
context=context,
)
# Detect project from memory URL prefix before routing
if project is None:
detected = detect_project_from_url_prefix(url, ConfigManager().config)
if detected:
project = detected
@@ -236,7 +207,7 @@ async def build_context(
entrypoint="mcp",
tool_name="build_context",
requested_project=project,
requested_project_id=project_id,
workspace_id=workspace,
depth=depth or 1,
timeframe=timeframe,
page=page,
@@ -245,10 +216,7 @@ async def build_context(
output_format=output_format,
is_memory_url=str(url).startswith("memory://"),
):
async with get_project_client(project, context=context, project_id=project_id) as (
client,
active_project,
):
async with get_project_client(project, workspace, context) as (client, active_project):
logger.info(
f"MCP tool call tool=build_context project={active_project.name} "
f"url={url} depth={depth} timeframe={timeframe} output_format={output_format}"
+4 -13
View File
@@ -8,7 +8,7 @@ from typing import Annotated, Dict, List, Any, Optional
from loguru import logger
from fastmcp import Context
from pydantic import AliasChoices, BeforeValidator, Field
from pydantic import BeforeValidator
from basic_memory.mcp.project_context import get_project_client
from basic_memory.utils import coerce_list
@@ -24,12 +24,9 @@ async def canvas(
nodes: Annotated[List[Dict[str, Any]], BeforeValidator(coerce_list)],
edges: Annotated[List[Dict[str, Any]], BeforeValidator(coerce_list)],
title: str,
directory: Annotated[
str,
Field(validation_alias=AliasChoices("directory", "folder", "dir", "path")),
],
directory: str,
project: Optional[str] = None,
project_id: Optional[str] = None,
workspace: Optional[str] = None,
context: Context | None = None,
) -> str:
"""Create an Obsidian canvas file with the provided nodes and edges.
@@ -46,9 +43,6 @@ async def canvas(
Args:
project: Project name to create canvas in. Optional - server will resolve using hierarchy.
If unknown, use list_memory_projects() to discover available projects.
project_id: Project external_id (UUID). Prefer this over `project` when known —
it routes to the exact project regardless of name collisions across cloud
workspaces. Takes precedence over `project`. Get from list_memory_projects().
nodes: List of node objects following JSON Canvas 1.0 spec
edges: List of edge objects following JSON Canvas 1.0 spec
title: The title of the canvas (will be saved as title.canvas)
@@ -103,10 +97,7 @@ async def canvas(
Raises:
ToolError: If project doesn't exist or directory path is invalid
"""
async with get_project_client(project, context=context, project_id=project_id) as (
client,
active_project,
):
async with get_project_client(project, workspace, context) as (client, active_project):
# Ensure path has .canvas extension
file_title = title if title.endswith(".canvas") else f"{title}.canvas"
file_path = f"{directory}/{file_title}"
+20 -29
View File
@@ -6,7 +6,7 @@ a list containing a single `{"type": "text", "text": "{...json...}"}` item.
"""
import json
from typing import Any, Dict, List, Optional, cast
from typing import Any, Dict, List, Optional
from fastmcp import Context
from loguru import logger
@@ -17,30 +17,18 @@ from basic_memory.mcp.tools.search import search_notes
from basic_memory.schemas.search import SearchResponse, SearchResult
def _identifier_for_read_note(identifier: str) -> str:
"""Convert ChatGPT result ids into routable Basic Memory identifiers."""
stripped = identifier.strip()
if stripped.startswith("memory://") or "/" not in stripped:
return identifier
return f"memory://{stripped}"
def _format_search_results_for_chatgpt(
results: SearchResponse | list[SearchResult | dict[str, Any]] | dict[str, Any],
results: SearchResponse | list[SearchResult] | list[dict[str, Any]] | dict[str, Any],
) -> List[Dict[str, Any]]:
"""Format search results according to ChatGPT's expected schema.
Returns a list of result objects with id, title, and url fields.
"""
if isinstance(results, SearchResponse):
raw_results: list[SearchResult | dict[str, Any]] = list(results.results)
raw_results: list[SearchResult] | list[dict[str, Any]] = results.results
elif isinstance(results, dict):
nested_results = results.get("results")
raw_results = (
cast(list[SearchResult | dict[str, Any]], nested_results)
if isinstance(nested_results, list)
else []
)
raw_results = nested_results if isinstance(nested_results, list) else []
else:
raw_results = results
@@ -125,7 +113,8 @@ async def search(
logger.info(f"ChatGPT search request: query='{query}'")
try:
# Keep this adapter tiny: the real search behavior lives in search_notes.
# Let search_notes resolve the default project via get_project_client(),
# which works in both local mode (ConfigManager) and cloud mode (database).
results = await search_notes(
query=query,
page=1,
@@ -134,6 +123,7 @@ async def search(
context=context,
)
# Handle string error responses from search_notes
if isinstance(results, str):
logger.warning(f"Search failed with error: {results[:100]}...")
search_results = {
@@ -141,17 +131,16 @@ async def search(
"error": "Search failed",
"error_details": results[:500], # Truncate long error messages
}
return [{"type": "text", "text": json.dumps(search_results, ensure_ascii=False)}]
raw_results = results.get("results", []) if isinstance(results, dict) else []
formatted_results = _format_search_results_for_chatgpt(raw_results)
search_results = {
"results": formatted_results,
"total_count": len(raw_results), # Use actual count from results
"query": query,
}
logger.info(f"Search completed: {len(formatted_results)} results returned")
else:
# Format successful results for ChatGPT
raw_results = results.get("results", []) if isinstance(results, dict) else []
formatted_results = _format_search_results_for_chatgpt(raw_results)
search_results = {
"results": formatted_results,
"total_count": len(raw_results), # Use actual count from results
"query": query,
}
logger.info(f"Search completed: {len(formatted_results)} results returned")
# Return in MCP content array format as required by OpenAI
return [{"type": "text", "text": json.dumps(search_results, ensure_ascii=False)}]
@@ -191,7 +180,9 @@ async def fetch(
# which works in both local mode (ConfigManager) and cloud mode (database).
content = str(
await read_note(
identifier=_identifier_for_read_note(id),
identifier=id,
page=1,
page_size=10,
context=context,
)
)
+10 -76
View File
@@ -1,21 +1,13 @@
from textwrap import dedent
from typing import Annotated, Optional, Literal
from typing import Optional, Literal
from loguru import logger
from fastmcp import Context
from mcp.server.fastmcp.exceptions import ToolError
from pydantic import AliasChoices, Field
from basic_memory.config import ConfigManager
from basic_memory.mcp.project_context import (
detect_project_from_memory_url_prefix,
get_project_client,
resolve_project_and_path,
)
from basic_memory.mcp.project_context import detect_project_from_url_prefix, get_project_client
from basic_memory.mcp.server import mcp
from basic_memory.schemas.project_info import ProjectItem
from basic_memory.utils import generate_permalink, normalize_project_reference
from basic_memory.workspace_context import current_workspace_permalink_context
def _format_delete_error_response(project: str, error_message: str, identifier: str) -> str:
@@ -155,44 +147,15 @@ delete_note("{project}", "correct-identifier-from-search")
If the note should be deleted but the operation keeps failing, send a message to support@basicmemory.com."""
def _directory_path_for_delete(
target_identifier: str,
active_project: ProjectItem,
*,
include_project_prefix: bool,
) -> str:
"""Return the project-relative directory path expected by the delete API."""
directory = normalize_project_reference(target_identifier).strip("/")
project_permalink = active_project.permalink
route_prefixes: list[str] = []
workspace_context = current_workspace_permalink_context()
if workspace_context and workspace_context.should_prefix_permalinks:
route_prefixes.append(
f"{generate_permalink(workspace_context.workspace_slug)}/{project_permalink}"
)
if include_project_prefix:
route_prefixes.append(project_permalink)
for route_prefix in route_prefixes:
if directory.startswith(f"{route_prefix}/"):
return directory.removeprefix(f"{route_prefix}/")
return directory
@mcp.tool(
description="Delete a note or directory by title, permalink, or path",
annotations={"destructiveHint": True, "openWorldHint": False},
)
async def delete_note(
identifier: str,
is_directory: Annotated[
bool,
Field(default=False, validation_alias=AliasChoices("is_directory", "is_dir")),
] = False,
is_directory: bool = False,
project: Optional[str] = None,
project_id: Optional[str] = None,
workspace: Optional[str] = None,
output_format: Literal["text", "json"] = "text",
context: Context | None = None,
) -> bool | str | dict:
@@ -216,9 +179,6 @@ async def delete_note(
(without file extensions). Defaults to False.
project: Project name to delete from. Optional - server will resolve using hierarchy.
If unknown, use list_memory_projects() to discover available projects.
project_id: Project external_id (UUID). Prefer this over `project` when known —
it routes to the exact project regardless of name collisions across cloud
workspaces. Takes precedence over `project`. Get from list_memory_projects().
output_format: "text" preserves existing behavior (bool/string). "json"
returns machine-readable deletion metadata.
context: Optional FastMCP context for performance caching.
@@ -264,23 +224,16 @@ async def delete_note(
commands and alternative formats to try.
"""
# Detect project from memory URL prefix before routing
# Trigger: identifier starts with memory:// and no explicit project/project_id was provided
# Trigger: identifier starts with memory:// and no explicit project was provided
# Why: only gate on memory:// to avoid misrouting plain paths like "research/note"
# where "research" is a directory, not a project name
# Outcome: project is set from the URL prefix, routing goes to the correct project
if project is None and project_id is None and identifier.strip().startswith("memory://"):
detected = await detect_project_from_memory_url_prefix(
identifier,
ConfigManager().config,
context=context,
)
if project is None and identifier.strip().startswith("memory://"):
detected = detect_project_from_url_prefix(identifier, ConfigManager().config)
if detected:
project = detected
async with get_project_client(project, context=context, project_id=project_id) as (
client,
active_project,
):
async with get_project_client(project, workspace, context) as (client, active_project):
logger.debug(
f"Deleting {'directory' if is_directory else 'note'}: {identifier} in project: {active_project.name}"
)
@@ -290,30 +243,11 @@ async def delete_note(
# Use typed KnowledgeClient for API calls
knowledge_client = KnowledgeClient(client, active_project.external_id)
_, target_identifier, is_memory_url = await resolve_project_and_path(
client,
identifier,
active_project.name,
context,
)
# Handle directory deletes
if is_directory:
try:
# Trigger: directory input was routed from a memory:// URL.
# Why: resolve_project_and_path returns canonical permalinks, while
# delete_directory filters by project-relative file_path prefixes.
# Outcome: strip only the route prefix before calling the delete API.
directory_identifier = (
_directory_path_for_delete(
target_identifier,
active_project,
include_project_prefix=ConfigManager().config.permalinks_include_project,
)
if is_memory_url
else target_identifier
)
result = await knowledge_client.delete_directory(directory_identifier)
result = await knowledge_client.delete_directory(identifier)
if output_format == "json":
return {
"deleted": result.failed_deletes == 0,
@@ -395,7 +329,7 @@ delete_note("path/to/file.md")
note_file_path = None
try:
# Resolve identifier to entity ID
entity_id = await knowledge_client.resolve_entity(target_identifier, strict=True)
entity_id = await knowledge_client.resolve_entity(identifier, strict=True)
if output_format == "json":
entity = await knowledge_client.get_entity(entity_id)
note_title = entity.title
+16 -155
View File
@@ -1,28 +1,21 @@
"""Edit note tool for Basic Memory MCP server."""
from typing import Annotated, Optional, Literal
from typing import Optional, Literal
import logfire
from loguru import logger
from fastmcp import Context
from pydantic import AliasChoices, Field
from basic_memory.config import ConfigManager
from basic_memory.mcp.project_context import (
_workspace_identifier_discovery_available,
detect_project_from_memory_url_prefix,
detect_project_from_url_prefix,
get_project_client,
add_project_metadata,
resolve_project_and_path,
)
from basic_memory.mcp.server import mcp
from basic_memory.schemas.base import Entity
from basic_memory.schemas.response import EntityResponse
from basic_memory.services.link_resolver import (
detect_project_from_workspace_identifier_prefix,
is_workspace_qualified_plain_identifier,
)
from basic_memory.utils import normalize_project_reference, validate_project_path
from basic_memory.utils import validate_project_path
def _parse_identifier_to_title_and_directory(identifier: str) -> tuple[str, str]:
@@ -52,58 +45,6 @@ def _parse_identifier_to_title_and_directory(identifier: str) -> tuple[str, str]
return title, directory
def _compose_workspace_project_route(
*,
workspace: Optional[str],
project: Optional[str],
project_id: Optional[str],
) -> Optional[str]:
"""Return the explicit project route requested by workspace/project args."""
if workspace is None:
return project
cleaned_workspace = workspace.strip().strip("/")
if not cleaned_workspace:
raise ValueError("workspace must not be empty when provided")
if "/" in cleaned_workspace:
raise ValueError("workspace must be a single workspace slug, name, or tenant_id")
if project_id is not None:
raise ValueError("workspace cannot be combined with project_id; use project_id alone")
if project is None or not project.strip().strip("/"):
raise ValueError("workspace requires an explicit project argument")
cleaned_project = project.strip().strip("/")
if "/" in cleaned_project:
raise ValueError(
"Use either workspace='workspace' with project='project', "
"or project='workspace/project', not both"
)
return f"{cleaned_workspace}/{cleaned_project}"
def _format_ambiguous_workspace_identifier_response(
*,
identifier: str,
detected_project: str,
) -> str:
"""Format the safe-stop response for ambiguous plain write identifiers."""
cleaned_identifier = identifier.strip()
normalized_identifier = normalize_project_reference(cleaned_identifier).strip("/")
workspace_hint, project_hint, note_identifier = normalized_identifier.split("/", 2)
return f"""# Edit Failed - Ambiguous Identifier
`{cleaned_identifier}` could refer to a local note path in the active project, or to a note in `{detected_project}`.
Because edit_note changes content, Basic Memory will not infer a workspace route from a plain path.
Retry with one of these explicit routes:
- `edit_note(identifier="{note_identifier}", project="{detected_project}", operation=..., content=...)`
- `edit_note(identifier="{note_identifier}", workspace="{workspace_hint}", project="{project_hint}", operation=..., content=...)`
- `edit_note(identifier="memory://{normalized_identifier}", operation=..., content=...)`
- `edit_note(identifier="{note_identifier}", project_id="<project external_id>", operation=..., content=...)`"""
def _format_error_response(
error_message: str,
operation: str,
@@ -229,34 +170,11 @@ Error editing note '{identifier}': {error_message}
async def edit_note(
identifier: str,
operation: str,
# Accept common replacement-content aliases. Models trained on diff/patch
# APIs reach for new_content/replacement/replace_with on first try.
content: Annotated[
str,
Field(
validation_alias=AliasChoices("content", "new_content", "replacement", "replace_with")
),
],
content: str,
project: Optional[str] = None,
workspace: Optional[str] = None,
project_id: Optional[str] = None,
# Section/heading naming varies across tools; accept the descriptive forms.
section: Annotated[
Optional[str],
Field(
default=None,
validation_alias=AliasChoices("section", "section_heading", "heading"),
),
] = None,
# find_text is the highest-frequency miss per the issue: models reach for
# find/old_text/old_content/search before find_text every time.
find_text: Annotated[
Optional[str],
Field(
default=None,
validation_alias=AliasChoices("find_text", "find", "old_text", "old_content", "search"),
),
] = None,
section: Optional[str] = None,
find_text: Optional[str] = None,
expected_replacements: Optional[int] = None,
output_format: Literal["text", "json"] = "text",
context: Context | None = None,
@@ -282,13 +200,7 @@ async def edit_note(
- "insert_after_section": Insert content after a section heading without consuming it (note must exist)
content: The content to add or use for replacement
project: Project name to edit in. Optional - server will resolve using hierarchy.
Use "workspace/project" to route to a project in a specific cloud workspace.
If unknown, use list_memory_projects() to discover available projects.
workspace: Workspace slug, name, or tenant_id. When provided with `project`,
routes as `workspace/project`. Cannot be combined with `project_id`.
project_id: Project external_id (UUID). Prefer this over `project` when known
it routes to the exact project regardless of name collisions across cloud
workspaces. Takes precedence over `project`. Get from list_memory_projects().
section: For replace_section operation - the markdown header to replace content under (e.g., "## Notes", "### Implementation")
find_text: For find_replace operation - the text to find and replace
expected_replacements: For find_replace operation - the expected number of replacements (validation will fail if actual doesn't match)
@@ -348,53 +260,14 @@ async def edit_note(
"""
# Resolve effective default: allow MCP clients to send null for optional int field
effective_replacements = expected_replacements if expected_replacements is not None else 1
project = _compose_workspace_project_route(
workspace=workspace,
project=project,
project_id=project_id,
)
# Resolve or reject routable identifier prefixes before selecting a client.
# Trigger: no explicit project/project_id was provided.
# Why: memory:// URLs are explicit routes, but plain three-segment identifiers
# are ambiguous for a mutating tool.
# Outcome: memory:// can route; plain workspace/project/path matches stop with
# guidance instead of silently editing another project.
if project is None and project_id is None:
config = ConfigManager().config
if identifier.strip().startswith("memory://"):
detected = await detect_project_from_memory_url_prefix(
identifier,
config,
context=context,
)
elif _workspace_identifier_discovery_available(
identifier,
config,
) and is_workspace_qualified_plain_identifier(identifier):
detected = await detect_project_from_workspace_identifier_prefix(
identifier,
config,
context=context,
)
if detected:
if output_format == "json":
return {
"title": None,
"permalink": None,
"file_path": None,
"checksum": None,
"operation": operation,
"fileCreated": False,
"error": "AMBIGUOUS_IDENTIFIER",
"project": detected,
}
return _format_ambiguous_workspace_identifier_response(
identifier=identifier,
detected_project=detected,
)
else:
detected = None
# Detect project from memory URL prefix before routing
# Trigger: identifier starts with memory:// and no explicit project was provided
# Why: only gate on memory:// to avoid misrouting plain paths like "research/note"
# where "research" is a directory, not a project name
# Outcome: project is set from the URL prefix, routing goes to the correct project
if project is None and identifier.strip().startswith("memory://"):
detected = detect_project_from_url_prefix(identifier, ConfigManager().config)
if detected:
project = detected
@@ -403,17 +276,14 @@ async def edit_note(
entrypoint="mcp",
tool_name="edit_note",
requested_project=project,
requested_project_id=project_id,
workspace_id=workspace,
edit_operation=operation,
output_format=output_format,
has_section=bool(section),
has_find_text=bool(find_text),
expected_replacements=effective_replacements,
):
async with get_project_client(project, context=context, project_id=project_id) as (
client,
active_project,
):
async with get_project_client(project, workspace, context) as (client, active_project):
logger.info(
f"MCP tool call tool=edit_note project={active_project.name} "
f"identifier={identifier} operation={operation} output_format={output_format}"
@@ -447,12 +317,6 @@ async def edit_note(
# Use typed KnowledgeClient for API calls
knowledge_client = KnowledgeClient(client, active_project.external_id)
_, entity_identifier, _ = await resolve_project_and_path(
client,
identifier,
active_project.name,
context,
)
file_created = False
entity_id = ""
@@ -460,10 +324,7 @@ async def edit_note(
# Try to resolve the entity; for append/prepend, create it if not found
try:
entity_id = await knowledge_client.resolve_entity(
entity_identifier,
strict=True,
)
entity_id = await knowledge_client.resolve_entity(identifier, strict=True)
except Exception as resolve_error:
# Trigger: entity does not exist yet
# Why: append/prepend can meaningfully create a new note from the content,
+5 -25
View File
@@ -1,10 +1,9 @@
"""List directory tool for Basic Memory MCP server."""
from typing import Annotated, Optional
from typing import Optional
from loguru import logger
from fastmcp import Context
from pydantic import AliasChoices, Field
from basic_memory.mcp.project_context import get_project_client
from basic_memory.mcp.server import mcp
@@ -15,24 +14,11 @@ from basic_memory.mcp.server import mcp
annotations={"readOnlyHint": True, "openWorldHint": False},
)
async def list_directory(
# `dir_name` is unusual; models reach for directory/folder/path/dir.
dir_name: Annotated[
str,
Field(
default="/",
validation_alias=AliasChoices("dir_name", "directory", "folder", "path", "dir"),
),
] = "/",
dir_name: str = "/",
depth: int = 1,
file_name_glob: Annotated[
Optional[str],
Field(
default=None,
validation_alias=AliasChoices("file_name_glob", "glob", "pattern", "filter"),
),
] = None,
file_name_glob: Optional[str] = None,
project: Optional[str] = None,
project_id: Optional[str] = None,
workspace: Optional[str] = None,
context: Context | None = None,
) -> str:
"""List directory contents from the knowledge base with optional filtering.
@@ -50,9 +36,6 @@ async def list_directory(
Examples: "*.md", "*meeting*", "project_*"
project: Project name to list directory from. Optional - server will resolve using hierarchy.
If unknown, use list_memory_projects() to discover available projects.
project_id: Project external_id (UUID). Prefer this over `project` when known
it routes to the exact project regardless of name collisions across cloud
workspaces. Takes precedence over `project`. Get from list_memory_projects().
context: Optional FastMCP context for performance caching.
Returns:
@@ -80,10 +63,7 @@ async def list_directory(
Raises:
ToolError: If project doesn't exist or directory path is invalid
"""
async with get_project_client(project, context=context, project_id=project_id) as (
client,
active_project,
):
async with get_project_client(project, workspace, context) as (client, active_project):
logger.debug(
f"Listing directory '{dir_name}' in project {project} with depth={depth}, glob='{file_name_glob}'"
)
+6 -31
View File
@@ -2,12 +2,11 @@
from pathlib import Path, PureWindowsPath
from textwrap import dedent
from typing import Annotated, Optional, Literal
from typing import Optional, Literal
from loguru import logger
from fastmcp import Context
from mcp.server.fastmcp.exceptions import ToolError
from pydantic import AliasChoices, Field
from basic_memory.mcp.server import mcp
from basic_memory.mcp.project_context import get_project_client
@@ -349,29 +348,11 @@ delete_note("{identifier}")
)
async def move_note(
identifier: str,
# Move/rename APIs across the ecosystem use `to`/`destination`/`new_path`.
destination_path: Annotated[
str,
Field(
default="",
validation_alias=AliasChoices(
"destination_path", "dest_path", "new_path", "to", "destination"
),
),
] = "",
destination_folder: Annotated[
Optional[str],
Field(
default=None,
validation_alias=AliasChoices("destination_folder", "dest_folder", "to_folder"),
),
] = None,
is_directory: Annotated[
bool,
Field(default=False, validation_alias=AliasChoices("is_directory", "is_dir")),
] = False,
destination_path: str = "",
destination_folder: Optional[str] = None,
is_directory: bool = False,
project: Optional[str] = None,
project_id: Optional[str] = None,
workspace: Optional[str] = None,
output_format: Literal["text", "json"] = "text",
context: Context | None = None,
) -> str | dict:
@@ -396,9 +377,6 @@ async def move_note(
(without file extensions). Defaults to False.
project: Project name to move within. Optional - server will resolve using hierarchy.
If unknown, use list_memory_projects() to discover available projects.
project_id: Project external_id (UUID). Prefer this over `project` when known
it routes to the exact project regardless of name collisions across cloud
workspaces. Takes precedence over `project`. Get from list_memory_projects().
output_format: "text" returns existing markdown guidance/success text. "json"
returns machine-readable move metadata.
context: Optional FastMCP context for performance caching.
@@ -498,10 +476,7 @@ async def move_note(
"error": "DESTINATION_FOLDER_NOT_FOR_DIRECTORIES",
}
return f"# Move Failed - Invalid Parameters\n\n{error_msg}"
async with get_project_client(project, context=context, project_id=project_id) as (
client,
active_project,
):
async with get_project_client(project, workspace, context) as (client, active_project):
destination_target = destination_folder or destination_path
logger.info(
f"MCP tool call tool=move_note project={active_project.name} "
+146 -217
View File
@@ -10,18 +10,8 @@ from typing import Literal
from fastmcp import Context
from loguru import logger
from basic_memory.config import (
BasicMemoryConfig,
ConfigManager,
ProjectEntry,
has_cloud_credentials,
)
from basic_memory.mcp.async_client import (
_explicit_routing,
_force_local_mode,
get_client,
is_factory_mode,
)
from basic_memory.config import ConfigManager, has_cloud_credentials
from basic_memory.mcp.async_client import get_client, get_cloud_proxy_client, is_factory_mode
from basic_memory.mcp.project_context import (
WorkspaceProjectEntry,
ensure_workspace_project_index,
@@ -35,6 +25,36 @@ from basic_memory.utils import generate_permalink
# --- Helpers for dual-fetch + merge ---
async def _fetch_cloud_projects(
workspace: str | None = None,
context: Context | None = None,
) -> ProjectList | None:
"""Fetch projects from the cloud API, returning None on failure.
Logs warnings on failure so list_memory_projects can fall back to local-only
results. Project-scoped routing does not use this listing fallback.
"""
try:
from basic_memory.mcp.clients import ProjectClient
async with get_cloud_proxy_client(workspace=workspace) as cloud_client:
cloud_project_client = ProjectClient(cloud_client)
cloud_list = await cloud_project_client.list_projects()
if context: # pragma: no cover
await context.info(f"Discovered {len(cloud_list.projects)} cloud projects")
return cloud_list
except Exception as exc:
logger.warning(
f"Cloud project discovery failed while listing projects; "
f"showing local-only project list: {exc}"
)
if context: # pragma: no cover
await context.info(
"Cloud project discovery failed while listing projects; showing local projects only"
)
return None
def _merge_projects(
local_list: ProjectList | None,
cloud_list: ProjectList | None,
@@ -106,13 +126,9 @@ def _merge_projects(
ws_type = cloud_workspace_type if cloud_proj else None
ws_tenant_id = cloud_workspace_tenant_id if cloud_proj else None
proj = cloud_proj or local_proj
external_id = proj.external_id if proj else None
merged.append(
{
"name": name,
"external_id": external_id,
"path": path,
"local_path": local_path,
"cloud_path": cloud_path,
@@ -136,66 +152,9 @@ def _merge_projects(
return merged
def _workspace_entry_priority(entry: WorkspaceProjectEntry) -> tuple[bool, int, str, str]:
"""Prefer default/personal workspaces when duplicate project permalinks exist."""
workspace_type_rank = 0 if entry.workspace.workspace_type == "personal" else 1
return (
# False sorts before True, so the cloud/default workspace comes first.
not entry.workspace.is_default,
workspace_type_rank,
entry.workspace.name.casefold(),
entry.workspace.tenant_id,
)
def _select_attached_cloud_entry(
cloud_entries: tuple[WorkspaceProjectEntry, ...],
*,
config_entry: ProjectEntry | None,
config: BasicMemoryConfig | None,
) -> WorkspaceProjectEntry | None:
"""Choose the single cloud row that should inherit local project state."""
if not cloud_entries:
return None
preferred_workspace_ids: list[str] = []
if config_entry and config_entry.workspace_id:
preferred_workspace_ids.append(config_entry.workspace_id)
if (
config
and config.default_workspace
and config.default_workspace not in preferred_workspace_ids
):
preferred_workspace_ids.append(config.default_workspace)
# The configured default workspace can differ from the cloud-side default.
# Use the cloud default only after explicit local config preferences.
default_workspace_entry = next(
(entry for entry in cloud_entries if entry.workspace.is_default),
None,
)
if (
default_workspace_entry is not None
and default_workspace_entry.workspace.tenant_id not in preferred_workspace_ids
):
preferred_workspace_ids.append(default_workspace_entry.workspace.tenant_id)
for workspace_id in preferred_workspace_ids:
for entry in cloud_entries:
if entry.workspace.tenant_id == workspace_id:
return entry
if len(cloud_entries) == 1:
return cloud_entries[0]
return sorted(cloud_entries, key=_workspace_entry_priority)[0]
def _merge_workspace_projects(
local_list: ProjectList | None,
cloud_entries: tuple[WorkspaceProjectEntry, ...],
*,
config: BasicMemoryConfig | None = None,
) -> list[dict]:
"""Merge local projects with cloud projects from every accessible workspace."""
local_by_permalink: dict[str, ProjectItem] = {}
@@ -203,40 +162,20 @@ def _merge_workspace_projects(
for project in local_list.projects:
local_by_permalink[project.permalink] = project
config_by_permalink: dict[str, ProjectEntry] = {}
if config:
config_by_permalink = {
generate_permalink(project_name): entry
for project_name, entry in config.projects.items()
}
cloud_entries_by_permalink: dict[str, list[WorkspaceProjectEntry]] = {}
for entry in cloud_entries:
cloud_entries_by_permalink.setdefault(entry.project.permalink, []).append(entry)
attached_entry_by_permalink: dict[str, WorkspaceProjectEntry | None] = {}
for permalink in local_by_permalink:
attached_entry_by_permalink[permalink] = _select_attached_cloud_entry(
tuple(cloud_entries_by_permalink.get(permalink, ())),
config_entry=config_by_permalink.get(permalink),
config=config,
)
cloud_permalinks = {entry.project.permalink for entry in cloud_entries}
merged: list[dict] = []
for entry in sorted(
cloud_entries,
key=lambda item: (*_workspace_entry_priority(item), item.project.permalink),
key=lambda item: (
not item.workspace.is_default,
item.workspace.workspace_type != "personal",
item.workspace.name.casefold(),
item.project.permalink,
),
):
permalink = entry.project.permalink
local_proj = (
local_by_permalink.get(permalink)
# WorkspaceProjectEntry is a frozen dataclass containing Pydantic
# models, so value equality is the intended comparison here.
if attached_entry_by_permalink.get(permalink) == entry
else None
)
local_proj = local_by_permalink.get(permalink)
cloud_proj = entry.project
source = "local+cloud" if local_proj else "cloud"
local_path = local_proj.path if local_proj else None
@@ -245,7 +184,6 @@ def _merge_workspace_projects(
merged.append(
{
"name": cloud_proj.name,
"external_id": cloud_proj.external_id,
"path": local_path or cloud_path,
"local_path": local_path,
"cloud_path": cloud_path,
@@ -269,7 +207,6 @@ def _merge_workspace_projects(
merged.append(
{
"name": project.name,
"external_id": project.external_id,
"path": project.path,
"local_path": project.path,
"cloud_path": None,
@@ -311,9 +248,9 @@ def _format_project_list_text(merged: list[dict]) -> str:
name = project["name"]
label = f"{display_name} ({name})" if display_name else name
source = project["source"]
external_id = project.get("external_id", "")
id_suffix = f" [{external_id}]" if external_id else ""
result += f"- {label} ({source}){id_suffix}\n"
qualified_name = project.get("qualified_name")
qualified_suffix = f" [{qualified_name}]" if qualified_name else ""
result += f"- {label} ({source}){qualified_suffix}\n"
result += "\n" + "" * 40 + "\n"
result += "Next: Ask which project to use for this session.\n"
@@ -345,6 +282,7 @@ def _format_project_list_json(
)
async def list_memory_projects(
output_format: Literal["text", "json"] = "text",
workspace: str | None = None,
context: Context | None = None,
) -> str | dict:
"""List all available projects with their status.
@@ -352,14 +290,11 @@ async def list_memory_projects(
Shows projects from both local and cloud sources when cloud credentials
are available, merging by permalink to give a unified view.
Each project entry includes an `external_id` (UUID). Pass that value as the
`project_id` parameter on other tools to address a specific project
unambiguously across cloud workspaces useful when the same project name
exists in more than one workspace.
Args:
output_format: "text" returns the existing human-readable project list.
"json" returns structured project metadata.
workspace: Cloud workspace name or tenant_id. Falls back to
config.default_workspace when not specified.
context: Optional FastMCP context for progress/status logging.
"""
if context: # pragma: no cover
@@ -372,20 +307,51 @@ async def list_memory_projects(
# --- Factory mode (cloud app) ---
# Trigger: set_client_factory() was called (e.g., basic-memory-cloud)
# Why: there is no local ASGI server; the factory IS the cloud source
# Outcome: fetch every accessible workspace so callers can discover cross-workspace IDs
# Outcome: single fetch, projects reported as source="cloud" with workspace metadata
if is_factory_mode():
workspace_index = await ensure_workspace_project_index(context=context)
merged = _merge_workspace_projects(None, workspace_index.entries)
default_project = next(
(
entry.project.name
for entry in workspace_index.entries
if entry.workspace.is_default and entry.project.is_default
),
async with get_client(workspace=workspace) as client:
project_client = ProjectClient(client)
project_list = await project_client.list_projects()
# Resolve workspace metadata so cloud projects carry their workspace info
cloud_ws_name: str | None = None
cloud_ws_type: str | None = None
cloud_ws_tenant_id: str | None = None
cloud_ws_slug: str | None = None
cloud_ws_is_default = False
try:
from basic_memory.mcp.project_context import get_available_workspaces
workspaces = await get_available_workspaces(context)
if workspaces:
# In factory mode the user is authenticated to a single workspace;
# use the explicit workspace param or fall back to the first available.
matched = None
if workspace:
matched = next((ws for ws in workspaces if ws.tenant_id == workspace), None)
if matched is None:
matched = workspaces[0]
cloud_ws_name = matched.name
cloud_ws_type = matched.workspace_type
cloud_ws_tenant_id = matched.tenant_id
cloud_ws_slug = matched.slug
cloud_ws_is_default = matched.is_default
except Exception:
pass # workspace lookup is best-effort
merged = _merge_projects(
None,
project_list,
cloud_workspace_name=cloud_ws_name,
cloud_workspace_type=cloud_ws_type,
cloud_workspace_tenant_id=cloud_ws_tenant_id,
cloud_workspace_slug=cloud_ws_slug,
cloud_workspace_is_default=cloud_ws_is_default,
)
if output_format == "json":
return _format_project_list_json(merged, default_project, constrained_project)
return _format_project_list_json(
merged, project_list.default_project, constrained_project
)
if constrained_project:
return _format_constrained_text(constrained_project)
return _format_project_list_text(merged)
@@ -406,22 +372,45 @@ async def list_memory_projects(
cloud_ws_is_default = False
config = ConfigManager().config
if has_cloud_credentials(config):
try:
workspace_index = await ensure_workspace_project_index(context=context)
cloud_entries = workspace_index.entries
except Exception as exc:
logger.warning(
f"Cloud workspace project index discovery failed while listing projects; "
f"showing local-only project list: {exc}"
)
if context: # pragma: no cover
await context.info(
"Cloud workspace project discovery failed while listing projects; "
"showing local projects only"
if workspace:
try:
active_workspace = await resolve_workspace_parameter(workspace, context)
except Exception as exc:
logger.warning(
f"Cloud workspace discovery failed while listing projects for "
f"workspace '{workspace}'; trying direct workspace routing before "
f"falling back to local-only project list: {exc}"
)
if context: # pragma: no cover
await context.info(
"Cloud workspace discovery failed while listing projects; "
"trying direct workspace routing"
)
cloud_list = await _fetch_cloud_projects(workspace, context)
else:
cloud_list = await _fetch_cloud_projects(active_workspace.tenant_id, context)
cloud_ws_name = active_workspace.name
cloud_ws_type = active_workspace.workspace_type
cloud_ws_tenant_id = active_workspace.tenant_id
cloud_ws_slug = active_workspace.slug
cloud_ws_is_default = active_workspace.is_default
else:
try:
workspace_index = await ensure_workspace_project_index(context=context)
cloud_entries = workspace_index.entries
except Exception as exc:
logger.warning(
f"Cloud workspace project index discovery failed while listing projects; "
f"showing local-only project list: {exc}"
)
if context: # pragma: no cover
await context.info(
"Cloud workspace project discovery failed while listing projects; "
"showing local projects only"
)
if cloud_entries:
merged = _merge_workspace_projects(local_list, cloud_entries, config=config)
merged = _merge_workspace_projects(local_list, cloud_entries)
else:
merged = _merge_projects(
local_list,
@@ -451,32 +440,6 @@ def _format_constrained_text(constrained_project: str) -> str:
return result
async def _resolve_workspace_routing(
workspace: str | None,
context: Context | None,
) -> str | None:
"""Resolve an optional workspace selector to the routing tenant id."""
if workspace is None:
return None
explicit_cloud_routing = _explicit_routing() and not _force_local_mode()
config = ConfigManager().config
should_resolve_workspace = is_factory_mode() or (
explicit_cloud_routing and has_cloud_credentials(config)
)
if not should_resolve_workspace:
return workspace
# Trigger: cloud routing can use workspace discovery and the caller supplied
# a friendly selector such as a slug, name, or tenant id.
# Why: MCP callers should not need to paste UUIDs, but the transport still
# uses X-Workspace-ID with the tenant id as its routing authority.
# Outcome: resolve once before the project-management request and pass only
# the tenant id downstream.
resolved_workspace = await resolve_workspace_parameter(workspace=workspace, context=context)
return resolved_workspace.tenant_id
@mcp.tool(
"create_memory_project",
annotations={"destructiveHint": False, "openWorldHint": False},
@@ -485,7 +448,6 @@ async def create_memory_project(
project_name: str,
project_path: str,
set_default: bool = False,
workspace: str | None = None,
output_format: Literal["text", "json"] = "text",
context: Context | None = None,
) -> str | dict:
@@ -498,11 +460,6 @@ async def create_memory_project(
project_name: Name for the new project (must be unique)
project_path: File system path where the project will be stored
set_default: Whether to set this project as the default (optional, defaults to False)
workspace: Optional cloud workspace selector to create the project in. Slug is
preferred for AI callers, but tenant_id and unique name are also accepted.
When omitted, the connection's default workspace is used. Discover values
via `list_workspaces`. In local mode the selector is passed through
without slug resolution.
output_format: "text" returns the existing human-readable result text.
"json" returns structured project creation metadata.
context: Optional FastMCP context for progress/status logging.
@@ -513,36 +470,26 @@ async def create_memory_project(
Example:
create_memory_project("my-research", "~/Documents/research")
create_memory_project("work-notes", "/home/user/work", set_default=True)
create_memory_project("team-notes", "/team/notes", workspace="team-paul")
"""
# Trigger: MCP server is constrained to a single project.
# Why: constrained sessions cannot create projects, and workspace selectors
# may be invalid or unavailable in that locked context.
# Outcome: return the existing disabled response before opening a routed client.
constrained_project = os.environ.get("BASIC_MEMORY_MCP_PROJECT")
if constrained_project:
if output_format == "json":
return {
"name": project_name,
"path": project_path,
"is_default": False,
"created": False,
"already_exists": False,
"error": "PROJECT_CONSTRAINED",
"message": (
f"Project creation disabled - MCP server is constrained to project "
f"'{constrained_project}'."
),
}
return f'# Error\n\nProject creation disabled - MCP server is constrained to project \'{constrained_project}\'.\nUse the CLI to create projects: `basic-memory project add "{project_name}" "{project_path}"`'
async with get_client() as client:
# Check if server is constrained to a specific project
constrained_project = os.environ.get("BASIC_MEMORY_MCP_PROJECT")
if constrained_project:
if output_format == "json":
return {
"name": project_name,
"path": project_path,
"is_default": False,
"created": False,
"already_exists": False,
"error": "PROJECT_CONSTRAINED",
"message": (
f"Project creation disabled - MCP server is constrained to project "
f"'{constrained_project}'."
),
}
return f'# Error\n\nProject creation disabled - MCP server is constrained to project \'{constrained_project}\'.\nUse the CLI to create projects: `basic-memory project add "{project_name}" "{project_path}"`'
workspace_id = await _resolve_workspace_routing(workspace, context)
# workspace targets a non-default cloud workspace at create time.
# Trigger: caller passed workspace (e.g. a slug discovered via list_workspaces).
# Why: there is no project_id yet for per-project routing — the project doesn't exist.
# Outcome: cloud factory routes the create request to the resolved workspace tenant id.
async with get_client(workspace=workspace_id) as client:
if context: # pragma: no cover
await context.info(f"Creating project: {project_name} at {project_path}")
@@ -568,7 +515,6 @@ async def create_memory_project(
if output_format == "json":
return {
"name": existing_match.name,
"external_id": existing_match.external_id,
"path": existing_match.path,
"is_default": is_default,
"created": False,
@@ -578,7 +524,6 @@ async def create_memory_project(
f"✓ Project already exists: {existing_match.name}\n\n"
f"Project Details:\n"
f"• Name: {existing_match.name}\n"
f"• External ID: {existing_match.external_id}\n"
f"• Path: {existing_match.path}\n"
f"{'• Set as default project\n' if is_default else ''}"
"\nProject is already available for use in tool calls.\n"
@@ -593,7 +538,6 @@ async def create_memory_project(
new_project = status_response.new_project
return {
"name": new_project.name if new_project else project_name,
"external_id": new_project.external_id if new_project else None,
"path": new_project.path if new_project else project_path,
"is_default": bool(
(new_project.is_default if new_project else False) or set_default
@@ -607,7 +551,6 @@ async def create_memory_project(
if status_response.new_project:
result += "Project Details:\n"
result += f"• Name: {status_response.new_project.name}\n"
result += f"• External ID: {status_response.new_project.external_id}\n"
result += f"• Path: {status_response.new_project.path}\n"
if set_default:
@@ -622,11 +565,7 @@ async def create_memory_project(
@mcp.tool(
annotations={"destructiveHint": True, "openWorldHint": False},
)
async def delete_project(
project_name: str,
workspace: str | None = None,
context: Context | None = None,
) -> str:
async def delete_project(project_name: str, context: Context | None = None) -> str:
"""Delete a Basic Memory project.
Removes a project from the configuration and database. This does NOT delete
@@ -635,33 +574,23 @@ async def delete_project(
Args:
project_name: Name of the project to delete
workspace: Optional cloud workspace selector to delete the project from.
Slug is preferred for AI callers, but tenant_id and unique name are
also accepted. When omitted, the connection's default workspace is
used. In local mode the selector is passed through without slug
resolution, matching create_memory_project behavior.
Returns:
Confirmation message about project deletion
Example:
delete_project("old-project")
delete_project("team-project", workspace="team-paul")
Warning:
This action cannot be undone. The project will need to be re-added
to access its content through Basic Memory again.
"""
# Trigger: MCP server is constrained to a single project.
# Why: constrained sessions cannot delete projects, and workspace selectors
# may be invalid or unavailable in that locked context.
# Outcome: return the existing disabled message before opening a routed client.
constrained_project = os.environ.get("BASIC_MEMORY_MCP_PROJECT")
if constrained_project:
return f"# Error\n\nProject deletion disabled - MCP server is constrained to project '{constrained_project}'.\nUse the CLI to delete projects: `basic-memory project remove \"{project_name}\"`"
async with get_client() as client:
# Check if server is constrained to a specific project
constrained_project = os.environ.get("BASIC_MEMORY_MCP_PROJECT")
if constrained_project:
return f"# Error\n\nProject deletion disabled - MCP server is constrained to project '{constrained_project}'.\nUse the CLI to delete projects: `basic-memory project remove \"{project_name}\"`"
workspace_id = await _resolve_workspace_routing(workspace, context)
async with get_client(workspace=workspace_id) as client:
if context: # pragma: no cover
await context.info(f"Deleting project: {project_name}")
+10 -27
View File
@@ -8,17 +8,16 @@ Files are read directly without any knowledge graph processing.
import base64
import io
from typing import Annotated, Optional
from typing import Optional
from loguru import logger
from PIL import Image as PILImage
from fastmcp import Context
from pydantic import AliasChoices, Field
from mcp.server.fastmcp.exceptions import ToolError
from basic_memory.config import ConfigManager
from basic_memory.mcp.project_context import (
detect_project_from_memory_url_prefix,
detect_project_from_url_prefix,
get_project_client,
resolve_project_and_path,
)
@@ -159,12 +158,9 @@ def optimize_image(img, content_length, max_output_bytes=350000):
annotations={"readOnlyHint": True, "openWorldHint": False},
)
async def read_content(
path: Annotated[
str,
Field(validation_alias=AliasChoices("path", "file_path", "filepath", "file")),
],
path: str,
project: Optional[str] = None,
project_id: Optional[str] = None,
workspace: Optional[str] = None,
context: Context | None = None,
) -> dict:
"""Read a file's raw content by path or permalink.
@@ -185,9 +181,6 @@ async def read_content(
- A permalink (docs/example)
project: Project name to read from. Optional - server will resolve using hierarchy.
If unknown, use list_memory_projects() to discover available projects.
project_id: Project external_id (UUID). Prefer this over `project` when known
it routes to the exact project regardless of name collisions across cloud
workspaces. Takes precedence over `project`. Get from list_memory_projects().
context: Optional FastMCP context for performance caching.
Returns:
@@ -217,27 +210,17 @@ async def read_content(
HTTPError: If project doesn't exist or is inaccessible
SecurityError: If path attempts path traversal
"""
# Detect project from memory URL prefix before routing.
# project_id routes by external UUID, so it bypasses URL discovery entirely.
if project is None and project_id is None:
detected = await detect_project_from_memory_url_prefix(
path,
ConfigManager().config,
context=context,
)
# Detect project from memory URL prefix before routing
if project is None:
detected = detect_project_from_url_prefix(path, ConfigManager().config)
if detected:
project = detected
logger.info(f"MCP tool call tool=read_content project={project} path={path}")
async with get_project_client(project, context=context, project_id=project_id) as (
client,
active_project,
):
# Resolve path with project-prefix awareness for memory:// URLs.
# Use active_project.name so resolution stays consistent when project_id
# was used or `project` was wrong/ambiguous (matches the cached resolution).
_, url, _ = await resolve_project_and_path(client, path, active_project.name, context)
async with get_project_client(project, workspace, context) as (client, active_project):
# Resolve path with project-prefix awareness for memory:// URLs
_, url, _ = await resolve_project_and_path(client, path, project, context)
# Validate path to prevent path traversal attacks
# For memory:// URLs, validate the extracted path (not the raw URL which
+29 -37
View File
@@ -11,7 +11,7 @@ from fastmcp import Context
from basic_memory.config import ConfigManager
from basic_memory.mcp.project_context import (
detect_project_from_identifier_prefix,
detect_project_from_url_prefix,
get_project_client,
resolve_project_and_path,
)
@@ -33,10 +33,10 @@ def _parse_opening_frontmatter(content: str) -> tuple[str, dict | None]:
If parsing fails or frontmatter is not a mapping, returns body unchanged and None.
"""
original_content = content
lines = content.splitlines(keepends=True)
if not lines or lines[0].strip() != "---":
if not content.startswith("---\n"):
return original_content, None
lines = content.splitlines(keepends=True)
closing_index = None
for i in range(1, len(lines)):
if lines[i].strip() == "---":
@@ -70,7 +70,9 @@ def _parse_opening_frontmatter(content: str) -> tuple[str, dict | None]:
async def read_note(
identifier: str,
project: Optional[str] = None,
project_id: Optional[str] = None,
workspace: Optional[str] = None,
page: int = 1,
page_size: int = 10,
output_format: Literal["text", "json"] = "text",
include_frontmatter: bool = False,
context: Context | None = None,
@@ -94,11 +96,10 @@ async def read_note(
project: Project name to read from. Optional - server will resolve using the
hierarchy above. If unknown, use list_memory_projects() to discover
available projects.
project_id: Project external_id (UUID). Prefer this over `project` when known
it routes to the exact project regardless of name collisions across cloud
workspaces. Takes precedence over `project`. Get from list_memory_projects().
identifier: The title or permalink of the note to read
Can be a full memory:// URL, a permalink, a title, or search text
page: Page number for paginated results (default: 1)
page_size: Number of items per page (default: 10)
output_format: "text" returns markdown content or guidance text.
"json" returns a structured object with title/permalink/file_path/content/frontmatter.
include_frontmatter: When output_format="json", whether content should include the
@@ -119,6 +120,9 @@ async def read_note(
# Read with memory URL
read_note("my-research", "memory://specs/search-spec")
# Read with pagination
read_note("work-project", "Project Updates", page=2, page_size=5)
# Read recent meeting notes
read_note("team-docs", "Weekly Standup")
@@ -130,14 +134,9 @@ async def read_note(
If the exact note isn't found, this tool provides helpful suggestions
including related notes, search commands, and note creation templates.
"""
# Detect project from a memory URL or permalink prefix before routing.
# project_id routes by external UUID, so it bypasses URL discovery entirely.
if project is None and project_id is None:
detected = await detect_project_from_identifier_prefix(
identifier,
ConfigManager().config,
context=context,
)
# Detect project from memory URL prefix before routing
if project is None:
detected = detect_project_from_url_prefix(identifier, ConfigManager().config)
if detected:
project = detected
@@ -146,21 +145,15 @@ async def read_note(
entrypoint="mcp",
tool_name="read_note",
requested_project=project,
requested_project_id=project_id,
workspace_id=workspace,
output_format=output_format,
page=page,
page_size=page_size,
include_frontmatter=include_frontmatter,
):
async with get_project_client(project, context=context, project_id=project_id) as (
client,
active_project,
):
# Resolve identifier with project-prefix awareness for memory:// URLs.
# Pass active_project.name (the canonical resolved name) rather than the
# original `project` arg so the inner get_active_project cache hits even
# when project_id was used or `project` was wrong/ambiguous.
_, entity_path, _ = await resolve_project_and_path(
client, identifier, active_project.name, context
)
async with get_project_client(project, workspace, context) as (client, active_project):
# Resolve identifier with project-prefix awareness for memory:// URLs
_, entity_path, _ = await resolve_project_and_path(client, identifier, project, context)
# Validate identifier to prevent path traversal attacks
# For memory:// URLs, validate the extracted path (not the raw URL which
@@ -211,7 +204,7 @@ async def read_note(
phase="shape_response",
):
entity = await knowledge_client.get_entity(entity_id)
response = await resource_client.read(entity_id)
response = await resource_client.read(entity_id, page=page, page_size=page_size)
content_text = response.text
body_content, parsed_frontmatter = _parse_opening_frontmatter(content_text)
return {
@@ -251,16 +244,14 @@ async def read_note(
# Why: search_notes applies the same memory:// normalization and tool-level
# query handling as the rest of MCP routing, which raw client calls skip.
# Outcome: unresolved memory URLs still fall back through normalized search.
# Pass project_id (external_id UUID) so the workspace selection from the
# outer get_project_client() is preserved across the inner re-resolution.
# Without this, project names that collide across workspaces could re-resolve
# to a different tenant via the default-workspace fallback (CLI/context=None).
search_type = "title" if title_only else "text"
response = await search_notes(
project=active_project.name,
project_id=active_project.external_id,
workspace=workspace,
query=identifier_text,
search_type=search_type,
page=page,
page_size=page_size,
output_format="json",
context=context,
)
@@ -282,13 +273,12 @@ async def read_note(
entity_id = await knowledge_client.resolve_entity(entity_path, strict=True)
# Fetch content using entity ID
response = await resource_client.read(entity_id)
response = await resource_client.read(entity_id, page=page, page_size=page_size)
# If successful, return the content
if response.status_code == 200:
logger.info(
"Returning read_note result from resource: {path}",
path=entity_path,
"Returning read_note result from resource: {path}", path=entity_path
)
if output_format == "json":
return await _read_json_payload(entity_id)
@@ -324,7 +314,9 @@ async def read_note(
)
# Fetch content using the entity ID
response = await resource_client.read(entity_id)
response = await resource_client.read(
entity_id, page=page, page_size=page_size
)
if response.status_code == 200:
logger.info(
+13 -41
View File
@@ -2,11 +2,10 @@
from datetime import timezone
from pathlib import PurePosixPath
from typing import Annotated, List, Union, Optional, Literal
from typing import List, Union, Optional, Literal
from loguru import logger
from fastmcp import Context
from pydantic import AliasChoices, Field
from basic_memory.mcp.async_client import get_client
from basic_memory.mcp.project_context import (
@@ -39,30 +38,13 @@ from basic_memory.schemas.search import SearchItemType
annotations={"readOnlyHint": True, "openWorldHint": False},
)
async def recent_activity(
type: Annotated[
Union[str, List[str]],
Field(default="", validation_alias=AliasChoices("type", "types", "kind")),
] = "",
type: Union[str, List[str]] = "",
depth: int = 1,
timeframe: Annotated[
TimeFrame,
Field(
default="7d",
validation_alias=AliasChoices("timeframe", "since", "time_range", "lookback"),
),
] = "7d",
# `offset` is intentionally NOT aliased: it has different semantics
# (item-indexed vs. 1-indexed page-number).
page: Annotated[
int,
Field(default=1, validation_alias=AliasChoices("page", "page_number")),
] = 1,
page_size: Annotated[
int,
Field(default=10, validation_alias=AliasChoices("page_size", "limit", "per_page")),
] = 10,
timeframe: TimeFrame = "7d",
page: int = 1,
page_size: int = 10,
project: Optional[str] = None,
project_id: Optional[str] = None,
workspace: Optional[str] = None,
output_format: Literal["text", "json"] = "text",
context: Context | None = None,
) -> str | list[dict]:
@@ -104,9 +86,6 @@ async def recent_activity(
project: Project name to query. Optional - server will resolve using the
hierarchy above. If unknown, use list_memory_projects() to discover
available projects.
project_id: Project external_id (UUID). Prefer this over `project` when known
it routes to the exact project regardless of name collisions across cloud
workspaces. Takes precedence over `project`. Get from list_memory_projects().
output_format: "text" returns human-readable summary text. "json" returns
a flat list of recent items.
context: Optional FastMCP context for performance caching.
@@ -182,14 +161,9 @@ async def recent_activity(
if "type" not in params:
params["type"] = [SearchItemType.ENTITY.value]
# Resolve project parameter using the three-tier hierarchy.
# allow_discovery=True enables Discovery Mode, so a project is not required.
# project_id (UUID) takes precedence over project name — without this fallback,
# callers passing only project_id would fall into Discovery Mode.
effective_identifier = project_id if project_id else project
resolved_project = await resolve_project_parameter(
effective_identifier, allow_discovery=True, context=context
)
# Resolve project parameter using the three-tier hierarchy
# allow_discovery=True enables Discovery Mode, so a project is not required
resolved_project = await resolve_project_parameter(project, allow_discovery=True)
if resolved_project is None:
# Discovery Mode: Get activity across all projects
@@ -304,7 +278,7 @@ async def recent_activity(
f"Getting recent activity from project {resolved_project}: type={type}, depth={depth}, timeframe={timeframe}"
)
async with get_project_client(resolved_project, context=context, project_id=project_id) as (
async with get_project_client(resolved_project, workspace, context) as (
client,
active_project,
):
@@ -490,12 +464,10 @@ def _format_project_output(
elif result.primary_result.type == "observation":
observations.append(result.primary_result)
# Show entities (notes/documents). Render every row the API returned —
# `page_size` is the single knob for how much comes back, so heading count
# and body row count always agree (regression: #784 silent truncation).
# Show entities (notes/documents)
if entities:
lines.append(f"\n**📄 Recent Notes & Documents ({len(entities)}):**")
for entity in entities:
for entity in entities[:5]: # Show top 5
title = entity.title or "Untitled"
# Get folder from file_path
folder = ""
@@ -528,7 +500,7 @@ def _format_project_output(
# Show relations (connections)
if relations:
lines.append(f"\n**🔗 Recent Connections ({len(relations)}):**")
for rel in relations:
for rel in relations[:5]: # Show top 5
rel_type = rel.relation_type
from_entity = rel.from_entity or "Unknown"
to_entity = rel.to_entity
+6 -24
View File
@@ -211,7 +211,7 @@ async def schema_validate(
note_type: Optional[str] = None,
identifier: Optional[str] = None,
project: Optional[str] = None,
project_id: Optional[str] = None,
workspace: Optional[str] = None,
output_format: Literal["text", "json"] = "text",
context: Context | None = None,
) -> ValidationReport | str | dict:
@@ -236,9 +236,6 @@ async def schema_validate(
identifier: Specific note to validate (permalink, title, or path).
If provided, validates only this note.
project: Project name. Optional -- server will resolve.
project_id: Project external_id (UUID). Prefer this over `project` when known
it routes to the exact project regardless of name collisions across cloud
workspaces. Takes precedence over `project`. Get from list_memory_projects().
context: Optional FastMCP context for performance caching.
Returns:
@@ -254,10 +251,7 @@ async def schema_validate(
# Validate in a specific project
schema_validate(note_type="person", project="my-research")
"""
async with get_project_client(project, context=context, project_id=project_id) as (
client,
active_project,
):
async with get_project_client(project, workspace, context) as (client, active_project):
logger.info(
f"MCP tool call tool=schema_validate project={active_project.name} "
f"note_type={note_type} identifier={identifier}"
@@ -324,7 +318,7 @@ async def schema_infer(
note_type: str,
threshold: float = 0.25,
project: Optional[str] = None,
project_id: Optional[str] = None,
workspace: Optional[str] = None,
output_format: Literal["text", "json"] = "text",
context: Context | None = None,
) -> str | dict:
@@ -348,9 +342,6 @@ async def schema_infer(
threshold: Minimum frequency (0-1) for a field to be suggested as optional.
Default 0.25 (25%). Fields above 95% become required.
project: Project name. Optional -- server will resolve.
project_id: Project external_id (UUID). Prefer this over `project` when known
it routes to the exact project regardless of name collisions across cloud
workspaces. Takes precedence over `project`. Get from list_memory_projects().
context: Optional FastMCP context for performance caching.
Returns:
@@ -366,10 +357,7 @@ async def schema_infer(
# Infer in a specific project
schema_infer("person", project="my-research")
"""
async with get_project_client(project, context=context, project_id=project_id) as (
client,
active_project,
):
async with get_project_client(project, workspace, context) as (client, active_project):
logger.info(
f"MCP tool call tool=schema_infer project={active_project.name} "
f"note_type={note_type} threshold={threshold}"
@@ -444,7 +432,7 @@ async def schema_infer(
async def schema_diff(
note_type: str,
project: Optional[str] = None,
project_id: Optional[str] = None,
workspace: Optional[str] = None,
output_format: Literal["text", "json"] = "text",
context: Context | None = None,
) -> str | dict:
@@ -465,9 +453,6 @@ async def schema_diff(
Args:
note_type: The note type to check for drift (e.g., "person").
project: Project name. Optional -- server will resolve.
project_id: Project external_id (UUID). Prefer this over `project` when known
it routes to the exact project regardless of name collisions across cloud
workspaces. Takes precedence over `project`. Get from list_memory_projects().
context: Optional FastMCP context for performance caching.
Returns:
@@ -481,10 +466,7 @@ async def schema_diff(
# Check drift in a specific project
schema_diff("person", project="my-research")
"""
async with get_project_client(project, context=context, project_id=project_id) as (
client,
active_project,
):
async with get_project_client(project, workspace, context) as (client, active_project):
logger.info(
f"MCP tool call tool=schema_diff project={active_project.name} note_type={note_type}"
)
+18 -362
View File
@@ -2,24 +2,18 @@
import re
from textwrap import dedent
from typing import Annotated, List, Optional, Dict, Any, Literal, cast
from uuid import UUID
from typing import Annotated, List, Optional, Dict, Any, Literal
import logfire
from loguru import logger
from fastmcp import Context
from pydantic import AliasChoices, BeforeValidator, Field
from pydantic import BeforeValidator
from basic_memory.config import ConfigManager, has_cloud_credentials
from basic_memory.utils import build_canonical_permalink, coerce_dict, coerce_list
from basic_memory.mcp.async_client import (
_explicit_routing,
_force_local_mode,
is_factory_mode,
)
from basic_memory.config import ConfigManager
from basic_memory.utils import coerce_dict, coerce_list
from basic_memory.mcp.container import get_container
from basic_memory.mcp.project_context import (
detect_project_from_identifier_prefix,
detect_project_from_url_prefix,
get_project_client,
resolve_project_and_path,
)
@@ -28,7 +22,6 @@ from basic_memory.schemas.search import (
SearchItemType,
SearchQuery,
SearchResponse,
SearchResult,
SearchRetrievalMode,
)
@@ -301,266 +294,6 @@ def _format_search_markdown(result: SearchResponse, project: str, query: str | N
return "\n".join(parts)
def _valid_project_id(value: object) -> str | None:
"""Return a UUID project id string when one is present."""
if not isinstance(value, str) or not value.strip():
return None
try:
return str(UUID(value))
except ValueError:
return None
def _matches_constrained_project(project: dict[str, Any], constrained_project: object) -> bool:
"""Return True when a project list row satisfies BASIC_MEMORY_MCP_PROJECT."""
if not isinstance(constrained_project, str) or not constrained_project.strip():
return True
candidates = {
value
for value in (
project.get("name"),
project.get("qualified_name"),
project.get("external_id"),
)
if isinstance(value, str)
}
return constrained_project in candidates
def _search_project_refs(projects_payload: object) -> list[dict[str, str | None]]:
"""Extract project routing refs for optional account-scoped search."""
if not isinstance(projects_payload, dict):
return []
payload = cast(dict[str, Any], projects_payload)
projects = payload.get("projects")
if not isinstance(projects, list):
return []
refs: list[dict[str, str | None]] = []
seen: set[tuple[str | None, str | None]] = set()
constrained_project = payload.get("constrained_project")
for item in projects:
if not isinstance(item, dict) or not _matches_constrained_project(
item, constrained_project
):
continue
project = item.get("qualified_name") or item.get("name")
project_name = project if isinstance(project, str) and project.strip() else None
project_id = _valid_project_id(item.get("external_id"))
if project_name is None and project_id is None:
continue
key = (project_name, project_id)
if key in seen:
continue
seen.add(key)
refs.append({"project": project_name, "project_id": project_id})
return refs
async def _load_search_project_refs(context: Context | None = None) -> list[dict[str, str | None]]:
"""Load accessible projects for search_all_projects without coupling the wrapper tool."""
from basic_memory.mcp.tools.project_management import list_memory_projects
return _search_project_refs(await list_memory_projects(output_format="json", context=context))
def _raw_results_from_search_payload(
results: SearchResponse | list[SearchResult | dict[str, Any]] | dict[str, Any],
) -> list[SearchResult | dict[str, Any]]:
"""Return the result list from any search_notes JSON-compatible payload."""
if isinstance(results, SearchResponse):
return list(results.results)
if isinstance(results, dict):
nested_results = results.get("results")
return (
cast(list[SearchResult | dict[str, Any]], nested_results)
if isinstance(nested_results, list)
else []
)
return list(results)
def _result_score(result: SearchResult | dict[str, Any]) -> float:
"""Return a comparable search score for merged project results."""
if isinstance(result, SearchResult):
return result.score
score = result.get("score")
return float(score) if isinstance(score, int | float) else 0.0
def _qualify_permalink_for_project(permalink: object, project: str | None) -> object:
"""Return a workspace-qualified permalink when the project ref supplies one."""
if not isinstance(permalink, str) or not permalink.strip():
return permalink
if not isinstance(project, str) or "/" not in project.strip("/"):
return permalink
normalized_permalink = permalink.strip("/")
qualified_project = project.strip("/")
if normalized_permalink == qualified_project or normalized_permalink.startswith(
f"{qualified_project}/"
):
return normalized_permalink
workspace_slug, project_permalink = qualified_project.split("/", 1)
return build_canonical_permalink(
project_permalink,
normalized_permalink,
include_project=True,
workspace_permalink=workspace_slug,
)
def _qualify_results_for_project(
results: list[SearchResult | dict[str, Any]],
project_ref: dict[str, str | None],
) -> list[dict[str, Any]]:
"""Attach the searched workspace/project prefix to each result permalink."""
qualified: list[dict[str, Any]] = []
for result in results:
if isinstance(result, SearchResult):
result_data = result.model_dump()
else:
result_data = dict(result)
result_data["permalink"] = _qualify_permalink_for_project(
result_data.get("permalink"),
project_ref.get("project"),
)
qualified.append(result_data)
return qualified
def _result_total(results: dict[str, Any], raw_results: list[SearchResult | dict[str, Any]]) -> int:
"""Return the best available total for a per-project search payload."""
total = results.get("total")
if isinstance(total, int) and total > 0:
return total
return len(raw_results) + (1 if results.get("has_more") is True else 0)
def _project_ref_label(project_ref: dict[str, str | None]) -> str:
"""Return a stable log label for a project search ref."""
return project_ref.get("project") or project_ref.get("project_id") or "<unknown project>"
async def _search_all_projects(
*,
query: str | None,
page: int,
page_size: int,
search_type: str | None,
output_format: Literal["text", "json"],
note_types: list[str],
entity_types: list[str],
after_date: str | None,
metadata_filters: dict[str, Any] | None,
tags: list[str] | None,
status: str | None,
min_similarity: float | None,
context: Context | None,
) -> dict | str:
"""Search every accessible project when the caller explicitly opts in."""
requested_page = max(page, 1)
requested_page_size = max(page_size, 1)
project_refs = await _load_search_project_refs(context=context)
if not project_refs:
response = SearchResponse(
results=[],
current_page=requested_page,
page_size=requested_page_size,
total=0,
has_more=False,
)
if output_format == "json":
return response.model_dump(mode="json", exclude_none=True)
return _format_search_markdown(response, "all projects", query)
per_project_page_size = requested_page * requested_page_size
merged_results: list[dict[str, Any]] = []
total = 0
any_project_has_more = False
# Trigger: caller asked for an account-wide search.
# Why: project_id (external UUID) routes through the cloud v2 API path,
# which 401s on local installs because there's no JWT to present.
# Project names route through the local-ASGI path and work for both
# backends — cloud disambiguates names via the workspace/project
# qualified_name already baked into project_ref["project"].
# Outcome: forward project_id only when the same signals get_project_client
# uses to pick a cloud route are present. Mirrors the cloud_available
# composite in project_context.get_project_client (single source of
# truth for "can we route to cloud?").
config = ConfigManager().config
use_cloud_routing = (
is_factory_mode()
or (_explicit_routing() and not _force_local_mode())
or has_cloud_credentials(config)
)
for project_ref in project_refs:
recursive_project_id = project_ref["project_id"] if use_cloud_routing else None
try:
results = await search_notes(
query=query,
project=project_ref["project"],
project_id=recursive_project_id,
page=1,
page_size=per_project_page_size,
search_type=search_type,
output_format="json",
note_types=note_types or None,
entity_types=entity_types or None,
after_date=after_date,
metadata_filters=metadata_filters,
tags=tags,
status=status,
min_similarity=min_similarity,
search_all_projects=False,
context=context,
)
except Exception as exc:
logger.warning(
f"Multi-project search failed for project {_project_ref_label(project_ref)}: {exc}"
)
continue
if isinstance(results, str):
if not results.startswith("# Search Failed"):
return results
logger.warning(
"Multi-project search failed for project "
f"{_project_ref_label(project_ref)}: {results}"
)
continue
raw_results = _raw_results_from_search_payload(results)
total += _result_total(results, raw_results)
any_project_has_more = any_project_has_more or results.get("has_more") is True
merged_results.extend(_qualify_results_for_project(raw_results, project_ref))
sorted_results = sorted(merged_results, key=_result_score, reverse=True)
start = (requested_page - 1) * requested_page_size
end = start + requested_page_size
paged_results = sorted_results[start:end]
response = SearchResponse.model_validate(
{
"results": paged_results,
"current_page": requested_page,
"page_size": requested_page_size,
"total": total,
"has_more": any_project_has_more or total > end or len(sorted_results) > end,
}
)
if output_format == "json":
return response.model_dump(mode="json", exclude_none=True)
return _format_search_markdown(response, "all projects", query)
@mcp.tool(
description="Search across all content in the knowledge base with advanced syntax support.",
# TODO: re-enable once MCP client rendering is working
@@ -568,58 +301,27 @@ async def _search_all_projects(
annotations={"readOnlyHint": True, "openWorldHint": False},
)
async def search_notes(
# Accept common search-query aliases models reach for from training data.
# `q` is the universal HTTP convention; `search`/`text` are common in NL APIs.
query: Annotated[
Optional[str],
Field(default=None, validation_alias=AliasChoices("query", "q", "search", "text")),
] = None,
query: Optional[str] = None,
project: Optional[str] = None,
project_id: Optional[str] = None,
search_all_projects: Annotated[
bool,
Field(
default=False,
validation_alias=AliasChoices("search_all_projects", "all_projects"),
),
] = False,
# `offset` is intentionally NOT aliased to `page`: offset is item-indexed
# (skip N items) while page is 1-indexed page-number. Direct aliasing would
# silently return the wrong slice.
page: Annotated[
int,
Field(default=1, validation_alias=AliasChoices("page", "page_number")),
] = 1,
page_size: Annotated[
int,
Field(default=10, validation_alias=AliasChoices("page_size", "limit", "per_page")),
] = 10,
workspace: Optional[str] = None,
page: int = 1,
page_size: int = 10,
search_type: str | None = None,
output_format: Literal["text", "json"] = "text",
# Plural-vs-singular trips models constantly. Accept the singular too.
note_types: Annotated[
List[str] | None,
BeforeValidator(coerce_list),
Field(default=None, validation_alias=AliasChoices("note_types", "note_type", "types")),
"Filter by the 'type' field in note frontmatter (e.g. 'note', 'chapter', 'person'). "
"Case-insensitive.",
] = None,
entity_types: Annotated[
List[str] | None,
BeforeValidator(coerce_list),
Field(default=None, validation_alias=AliasChoices("entity_types", "entity_type")),
"Filter by knowledge graph item type: 'entity' (whole notes), 'observation', or "
"'relation'. Defaults to 'entity'. Do NOT pass schema/frontmatter types like "
"'Chapter' here — use note_types instead.",
] = None,
# Time-filter naming varies wildly across APIs.
after_date: Annotated[
Optional[str],
Field(
default=None,
validation_alias=AliasChoices("after_date", "since", "after", "from_date"),
),
] = None,
after_date: Optional[str] = None,
metadata_filters: Annotated[
Dict[str, Any] | None,
BeforeValidator(coerce_dict),
@@ -629,13 +331,7 @@ async def search_notes(
BeforeValidator(coerce_list),
] = None,
status: Optional[str] = None,
min_similarity: Annotated[
Optional[float],
Field(
default=None,
validation_alias=AliasChoices("min_similarity", "threshold", "similarity_threshold"),
),
] = None,
min_similarity: Optional[float] = None,
context: Context | None = None,
) -> dict | str:
"""Search across all content in the knowledge base with comprehensive syntax support.
@@ -647,8 +343,6 @@ async def search_notes(
Project Resolution:
Server resolves projects in this order: Single Project Mode project parameter default project.
If project unknown, use list_memory_projects() or recent_activity() first.
Set search_all_projects=True to search every accessible project; this is opt-in because it
performs one search per project.
## Search Syntax Examples
@@ -721,11 +415,6 @@ async def search_notes(
Omit or pass None for filter-only searches using metadata_filters, tags, or status.
project: Project name to search in. Optional - server will resolve using hierarchy.
If unknown, use list_memory_projects() to discover available projects.
project_id: Project external_id (UUID). Prefer this over `project` when known
it routes to the exact project regardless of name collisions across cloud
workspaces. Takes precedence over `project`. Get from list_memory_projects().
search_all_projects: Optional opt-in to search every accessible project. Ignored when
`project` or `project_id` is supplied.
page: The page number of results to return (default 1)
page_size: The number of results to return per page (default 10)
search_type: Type of search to perform, one of:
@@ -829,46 +518,18 @@ async def search_notes(
remainder = re.sub(r"\b(AND|OR|NOT)\b", "", remainder).strip()
query = remainder or None
# Detect project from a memory URL or permalink prefix before routing.
# project_id routes by external UUID, so it bypasses URL discovery entirely.
if project is None and project_id is None and query is not None:
detected = await detect_project_from_identifier_prefix(
query,
ConfigManager().config,
context=context,
)
# Detect project from memory URL prefix before routing
if project is None and query is not None:
detected = detect_project_from_url_prefix(query, ConfigManager().config)
if detected:
project = detected
# Trigger: caller explicitly requests account/workspace-wide search and did not
# already provide a concrete project route.
# Why: multi-project fan-out can be slow, so default search remains project-scoped.
# Outcome: run one normal search per accessible project and merge ranked results.
if search_all_projects and project is None and project_id is None:
all_projects_result = await _search_all_projects(
query=query,
page=page,
page_size=page_size,
search_type=search_type,
output_format=output_format,
note_types=note_types,
entity_types=entity_types,
after_date=after_date,
metadata_filters=metadata_filters,
tags=tags,
status=status,
min_similarity=min_similarity,
context=context,
)
return all_projects_result
with logfire.span(
"mcp.tool.search_notes",
entrypoint="mcp",
tool_name="search_notes",
requested_project=project,
requested_project_id=project_id,
search_all_projects=search_all_projects,
workspace_id=workspace,
search_type=search_type or "default",
output_format=output_format,
page=page,
@@ -882,17 +543,12 @@ async def search_notes(
has_tags_filter=bool(tags),
has_status_filter=bool(status),
):
async with get_project_client(project, context=context, project_id=project_id) as (
client,
active_project,
):
# Handle memory:// URLs by resolving to permalink search.
# Use active_project.name so resolution hits the cached active project
# when project_id was used or `project` was wrong/ambiguous.
async with get_project_client(project, workspace, context) as (client, active_project):
# Handle memory:// URLs by resolving to permalink search
is_memory_url = False
if query is not None:
_, resolved_query, is_memory_url = await resolve_project_and_path(
client, query, active_project.name, context
client, query, project, context
)
if is_memory_url:
query = resolved_query
+6 -4
View File
@@ -25,7 +25,6 @@ def _text_block(message: str) -> List[ContentBlock]:
async def search_notes_ui(
query: str,
project: Optional[str] = None,
project_id: Optional[str] = None,
page: int = 1,
page_size: int = 10,
search_type: Optional[str] = None,
@@ -50,7 +49,6 @@ async def search_notes_ui(
result = await search_notes(
query=query,
project=project,
project_id=project_id,
page=page,
page_size=page_size,
search_type=search_type,
@@ -99,14 +97,16 @@ async def search_notes_ui(
async def read_note_ui(
identifier: str,
project: Optional[str] = None,
project_id: Optional[str] = None,
page: int = 1,
page_size: int = 10,
context: Context | None = None,
) -> List[ContentBlock]:
"""Return a note preview UI as an embedded MCP-UI resource."""
content = await read_note(
identifier=identifier,
project=project,
project_id=project_id,
page=page,
page_size=page_size,
output_format="text",
context=context,
)
@@ -114,6 +114,8 @@ async def read_note_ui(
render_data = {
"toolInput": {
"identifier": identifier,
"page": page,
"page_size": page_size,
},
"toolOutput": content,
}
+6 -22
View File
@@ -8,7 +8,7 @@ import typing
from typing import Any, Optional
import logfire
from httpx import Response, URL, AsyncClient, HTTPStatusError, Headers
from httpx import Response, URL, AsyncClient, HTTPStatusError
from httpx._client import UseClientDefault, USE_CLIENT_DEFAULT
from httpx._types import (
RequestContent,
@@ -58,22 +58,6 @@ def _transport_error_span_attrs(exc: Exception) -> dict[str, Any]:
}
def _request_headers(headers: HeaderTypes | None) -> HeaderTypes | None:
"""Merge request-local workspace permalink headers into outbound API calls."""
from basic_memory.workspace_context import workspace_permalink_headers
workspace_headers = workspace_permalink_headers()
if not workspace_headers:
return headers
if headers is None:
return workspace_headers
merged_headers = Headers(headers)
merged_headers.update(workspace_headers)
return merged_headers
def get_error_message(
status_code: int, url: URL | str, method: str, msg: Optional[str] = None
) -> str:
@@ -240,7 +224,7 @@ async def call_get(
response = await client.get(
url,
params=params,
headers=_request_headers(headers),
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
@@ -344,7 +328,7 @@ async def call_put(
files=files,
json=json,
params=params,
headers=_request_headers(headers),
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
@@ -448,7 +432,7 @@ async def call_patch(
files=files,
json=json,
params=params,
headers=_request_headers(headers),
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
@@ -558,7 +542,7 @@ async def call_post(
files=files,
json=json,
params=params,
headers=_request_headers(headers),
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
@@ -683,7 +667,7 @@ async def call_delete(
response = await client.delete(
url=url,
params=params,
headers=_request_headers(headers),
headers=headers,
cookies=cookies,
auth=auth,
follow_redirects=follow_redirects,
+11 -5
View File
@@ -17,7 +17,9 @@ from basic_memory.mcp.tools.read_note import read_note
async def view_note(
identifier: str,
project: Optional[str] = None,
project_id: Optional[str] = None,
workspace: Optional[str] = None,
page: int = 1,
page_size: int = 10,
context: Context | None = None,
) -> str:
"""View a markdown note as a formatted artifact.
@@ -30,9 +32,8 @@ async def view_note(
identifier: The title or permalink of the note to view
project: Project name to read from. Optional - server will resolve using hierarchy.
If unknown, use list_memory_projects() to discover available projects.
project_id: Project external_id (UUID). Prefer this over `project` when known
it routes to the exact project regardless of name collisions across cloud
workspaces. Takes precedence over `project`. Get from list_memory_projects().
page: Page number for paginated results (default: 1)
page_size: Number of items per page (default: 10)
context: Optional FastMCP context for performance caching.
Returns:
@@ -45,6 +46,9 @@ async def view_note(
# View a note by permalink
view_note("meetings/weekly-standup")
# View with pagination
view_note("large-document", page=2, page_size=5)
# Explicit project specification
view_note("Meeting Notes", project="my-project")
@@ -59,7 +63,9 @@ async def view_note(
await read_note(
identifier=identifier,
project=project,
project_id=project_id,
workspace=workspace,
page=page,
page_size=page_size,
context=context,
)
)
+10 -39
View File
@@ -5,20 +5,14 @@ from typing import Annotated, List, Union, Optional, Literal
import logfire
from loguru import logger
from pydantic import AliasChoices, BeforeValidator, Field
from pydantic import BeforeValidator
from basic_memory.config import ConfigManager
from basic_memory.mcp.project_context import get_project_client, add_project_metadata
from basic_memory.mcp.server import mcp
from fastmcp import Context
from basic_memory.schemas.base import Entity
from basic_memory.utils import (
build_qualified_permalink_reference,
coerce_dict,
parse_tags,
validate_project_path,
)
from basic_memory.workspace_context import current_workspace_permalink_context
from basic_memory.utils import coerce_dict, parse_tags, validate_project_path
# Define TagType as a Union that can accept either a string or a list of strings or None
TagType = Union[List[str], str, None]
@@ -31,13 +25,9 @@ TagType = Union[List[str], str, None]
async def write_note(
title: str,
content: str,
# Folder/dir/path are interchangeable in models' training data.
directory: Annotated[
str,
Field(validation_alias=AliasChoices("directory", "folder", "dir", "path")),
],
directory: str,
project: Optional[str] = None,
project_id: Optional[str] = None,
workspace: Optional[str] = None,
tags: list[str] | str | None = None,
note_type: str = "note",
metadata: Annotated[dict | None, BeforeValidator(coerce_dict)] = None,
@@ -68,14 +58,10 @@ async def write_note(
Relations format:
- Explicit: `- relation_type [[Entity]] (optional context)`
- Quoted: `- "multi word relation type" [[Entity]] (optional context)`
- Quoted: `- 'multi word relation type' [[Entity]] (optional context)`
- Inline: Any other `[[Entity]]` reference creates a `links_to` relation
- Inline: Any `[[Entity]]` reference creates a relation
Examples:
`- depends_on [[Content Parser]] (Need for semantic extraction)`
`- "based on" [[Design Notes]]`
`- 'in response to' [[Incident Review]]`
`- implements [[Search Spec]] (Initial implementation)`
`- This feature extends [[Base Design]] and uses [[Core Utils]]`
@@ -88,9 +74,6 @@ async def write_note(
project: Project name to write to. Optional - server will resolve using the
hierarchy above. If unknown, use list_memory_projects() to discover
available projects.
project_id: Project external_id (UUID). Prefer this over `project` when known
it routes to the exact project regardless of name collisions across cloud
workspaces. Takes precedence over `project`. Get from list_memory_projects().
tags: Tags to categorize the note. Can be a list of strings, a comma-separated string, or None.
Note: If passing from external MCP clients, use a string format (e.g. "tag1,tag2,tag3")
note_type: Type of note to create (stored in frontmatter). Defaults to "note".
@@ -171,15 +154,12 @@ async def write_note(
entrypoint="mcp",
tool_name="write_note",
requested_project=project,
requested_project_id=project_id,
workspace_id=workspace,
note_type=note_type,
overwrite=effective_overwrite,
output_format=output_format,
):
async with get_project_client(project, context=context, project_id=project_id) as (
client,
active_project,
):
async with get_project_client(project, workspace, context) as (client, active_project):
logger.info(
f"MCP tool call tool=write_note project={active_project.name} directory={directory}, title={title}, tags={tags}"
)
@@ -280,20 +260,11 @@ async def write_note(
else:
# Re-raise if it's not a conflict error
raise # pragma: no cover
response_permalink = result.permalink
workspace_context = current_workspace_permalink_context()
if response_permalink and workspace_context is not None:
response_permalink = build_qualified_permalink_reference(
active_project.permalink,
response_permalink,
workspace_permalink=workspace_context.workspace_slug,
)
summary = [
f"# {action} note",
f"project: {active_project.name}",
f"file_path: {result.file_path}",
f"permalink: {response_permalink}",
f"permalink: {result.permalink}",
f"checksum: {result.checksum[:8] if result.checksum else 'unknown'}",
]
@@ -330,12 +301,12 @@ async def write_note(
# Log the response with structured data
logger.info(
f"MCP tool response: tool=write_note project={active_project.name} action={action} permalink={response_permalink} observations_count={len(result.observations)} relations_count={len(result.relations)} resolved_relations={resolved} unresolved_relations={unresolved}"
f"MCP tool response: tool=write_note project={active_project.name} action={action} permalink={result.permalink} observations_count={len(result.observations)} relations_count={len(result.relations)} resolved_relations={resolved} unresolved_relations={unresolved}"
)
if output_format == "json":
return {
"title": result.title,
"permalink": response_permalink,
"permalink": result.permalink,
"file_path": result.file_path,
"checksum": result.checksum,
"action": action.lower(),
@@ -8,7 +8,7 @@ from loguru import logger
from sqlalchemy import exists, func, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from sqlalchemy.orm import load_only, selectinload
from sqlalchemy.orm import selectinload
from sqlalchemy.orm.interfaces import LoaderOption
from sqlalchemy.engine import Row
@@ -178,24 +178,6 @@ class EntityRepository(Repository[Entity]):
result = await self.execute_query(query, use_query_options=False)
return list(result.scalars().all())
async def find_by_ids_for_hydration(self, ids: List[int]) -> Sequence[Entity]:
"""Fetch minimal entity fields needed for context hydration.
Context hydration only needs an entity's primary key, title, and external
UUID. Keeping this separate from find_by_ids avoids the relationship eager
loads that are useful for full entity reads but expensive for response shaping.
"""
if not ids:
return []
query = (
self.select()
.where(Entity.id.in_(ids))
.options(load_only(Entity.id, Entity.title, Entity.external_id))
)
result = await self.execute_query(query, use_query_options=False)
return list(result.scalars().all())
async def get_permalink_to_file_path_map(self) -> dict[str, str]:
"""Get a mapping of permalink -> file_path for all entities.
@@ -455,18 +437,28 @@ class EntityRepository(Repository[Entity]):
return list(result.scalars().all())
async def find_without_relations(self) -> Sequence[Entity]:
"""Find entities that have no incoming or outgoing relations."""
# Trigger: entity appears as a source in any relation.
# Why: even unresolved outgoing links mean the entity references another node.
# Outcome: entities with outgoing relations are excluded from the orphan list.
"""Find entities that have no incoming or outgoing relations.
An orphan entity has no entries as from_id in any relation and no resolved
entries as to_id. These are isolated nodes in the knowledge graph.
Returns:
Sequence of entities with no outgoing or incoming relations
"""
# Trigger: entity appears as a source in any relation (outgoing link)
# Why: even unresolved outgoing links mean the entity references something
# Outcome: entities with any outgoing relation are excluded
has_outgoing = exists().where(Relation.from_id == Entity.id)
# Trigger: entity appears as the resolved target in any relation.
# Why: only resolved relation targets are graph nodes with an incoming edge.
# Outcome: entities referenced by resolved links are excluded from orphans.
has_incoming = exists().where(Relation.to_id == Entity.id)
# Trigger: entity appears as a resolved target in any relation (incoming link)
# Why: to_id is null for unresolved links; only resolved links form graph edges
# Outcome: entities referenced by resolved links are excluded
has_incoming = exists().where(
Relation.to_id == Entity.id,
Relation.to_id.is_not(None),
)
query = self.select().where(~has_outgoing).where(~has_incoming).order_by(Entity.file_path)
query = self.select().where(~has_outgoing).where(~has_incoming)
result = await self.execute_query(query, use_query_options=False)
return list(result.scalars().all())
@@ -5,17 +5,11 @@ from __future__ import annotations
from dataclasses import dataclass
from datetime import date, datetime
import re
from typing import Any, Iterable, List, cast
from typing import Any, Iterable, List
_KEY_RE = re.compile(r"^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$")
_NUMERIC_RE = re.compile(r"^-?\d+(\.\d+)?$")
_COMPARISON_OPERATORS = {
"$gt": "gt",
"$gte": "gte",
"$lt": "lt",
"$lte": "lte",
}
@dataclass(frozen=True)
@@ -54,11 +48,6 @@ def _normalize_scalar(value: Any) -> Any:
return value
def _normalize_numeric(value: object) -> float:
"""Normalize a value already proven numeric by _is_numeric_value."""
return float(cast(str | int | float, value))
def parse_metadata_filters(filters: dict[str, Any]) -> List[ParsedMetadataFilter]:
"""Parse metadata filters into normalized clauses.
@@ -84,12 +73,7 @@ def parse_metadata_filters(filters: dict[str, Any]) -> List[ParsedMetadataFilter
if isinstance(raw_value, dict):
if len(raw_value) != 1:
raise ValueError(f"Invalid metadata filter for '{raw_key}': {raw_value}")
raw_op, value = next(iter(raw_value.items()))
if not isinstance(raw_op, str):
raise ValueError(
f"Unsupported operator '{raw_op}' in metadata filter for '{raw_key}'"
)
op = raw_op
op, value = next(iter(raw_value.items()))
if op == "$in":
if not isinstance(value, list) or not value:
@@ -99,20 +83,15 @@ def parse_metadata_filters(filters: dict[str, Any]) -> List[ParsedMetadataFilter
)
continue
if op in _COMPARISON_OPERATORS:
if op in {"$gt", "$gte", "$lt", "$lte"}:
if _is_numeric_value(value):
normalized = _normalize_numeric(value)
normalized = float(value)
comparison = "numeric"
else:
normalized = _normalize_scalar(value)
comparison = "text"
parsed.append(
ParsedMetadataFilter(
path_parts,
_COMPARISON_OPERATORS[op],
normalized,
comparison,
)
ParsedMetadataFilter(path_parts, op.lstrip("$"), normalized, comparison)
)
continue
@@ -120,7 +99,7 @@ def parse_metadata_filters(filters: dict[str, Any]) -> List[ParsedMetadataFilter
if not isinstance(value, list) or len(value) != 2:
raise ValueError(f"$between requires [min, max] for '{raw_key}'")
if _is_numeric_collection(value):
normalized = [_normalize_numeric(v) for v in value]
normalized = [float(v) for v in value]
comparison = "numeric"
else:
normalized = [_normalize_scalar(v) for v in value]
@@ -686,17 +686,7 @@ class PostgresSearchRepository(SearchRepositoryBase):
# FTS search (Postgres-specific)
# ------------------------------------------------------------------
@staticmethod
def _is_tsquery_syntax_error(exc: Exception) -> bool:
msg = str(exc).lower()
return (
"syntax error in tsquery" in msg
or "invalid input syntax for type tsquery" in msg
or "no operand in tsquery" in msg
or "no operator in tsquery" in msg
)
async def _build_fts_query_parts(
async def search(
self,
search_text: Optional[str] = None,
permalink: Optional[str] = None,
@@ -706,8 +696,31 @@ class PostgresSearchRepository(SearchRepositoryBase):
after_date: Optional[datetime] = None,
search_item_types: Optional[List[SearchItemType]] = None,
metadata_filters: Optional[dict] = None,
) -> tuple[str, str, dict, str, str]:
"""Build Postgres FTS FROM/WHERE params shared by search and count."""
retrieval_mode: SearchRetrievalMode = SearchRetrievalMode.FTS,
min_similarity: Optional[float] = None,
limit: int = 10,
offset: int = 0,
) -> List[SearchIndexRow]:
"""Search across all indexed content using PostgreSQL tsvector."""
# --- Dispatch vector / hybrid modes (shared logic) ---
dispatched = await self._dispatch_retrieval_mode(
search_text=search_text,
permalink=permalink,
permalink_match=permalink_match,
title=title,
note_types=note_types,
after_date=after_date,
search_item_types=search_item_types,
metadata_filters=metadata_filters,
retrieval_mode=retrieval_mode,
min_similarity=min_similarity,
limit=limit,
offset=offset,
)
if dispatched is not None:
return dispatched
# --- FTS mode (Postgres-specific) ---
conditions = []
params = {}
order_by_clause = ""
@@ -774,8 +787,7 @@ class PostgresSearchRepository(SearchRepositoryBase):
# Handle date filter
if after_date:
params["after_date"] = after_date
# Filter on updated_at so recently-edited notes are included even when created_at is old
conditions.append("search_index.updated_at > :after_date")
conditions.append("search_index.created_at > :after_date")
# order by most recent first
order_by_clause = ", search_index.updated_at DESC"
@@ -856,6 +868,10 @@ class PostgresSearchRepository(SearchRepositoryBase):
params["project_id"] = self.project_id
conditions.append("search_index.project_id = :project_id")
# set limit and offset
params["limit"] = limit
params["offset"] = offset
# Build WHERE clause
where_clause = " AND ".join(conditions) if conditions else "1=1"
@@ -868,64 +884,6 @@ class PostgresSearchRepository(SearchRepositoryBase):
else:
score_expr = "0"
return from_clause, where_clause, params, order_by_clause, score_expr
async def search(
self,
search_text: Optional[str] = None,
permalink: Optional[str] = None,
permalink_match: Optional[str] = None,
title: Optional[str] = None,
note_types: Optional[List[str]] = None,
after_date: Optional[datetime] = None,
search_item_types: Optional[List[SearchItemType]] = None,
metadata_filters: Optional[dict] = None,
retrieval_mode: SearchRetrievalMode = SearchRetrievalMode.FTS,
min_similarity: Optional[float] = None,
limit: int = 10,
offset: int = 0,
) -> List[SearchIndexRow]:
"""Search across all indexed content using PostgreSQL tsvector."""
# --- Dispatch vector / hybrid modes (shared logic) ---
dispatched = await self._dispatch_retrieval_mode(
search_text=search_text,
permalink=permalink,
permalink_match=permalink_match,
title=title,
note_types=note_types,
after_date=after_date,
search_item_types=search_item_types,
metadata_filters=metadata_filters,
retrieval_mode=retrieval_mode,
min_similarity=min_similarity,
limit=limit,
offset=offset,
)
if dispatched is not None:
return dispatched
# --- FTS mode (Postgres-specific) ---
(
from_clause,
where_clause,
params,
order_by_clause,
score_expr,
) = await self._build_fts_query_parts(
search_text=search_text,
permalink=permalink,
permalink_match=permalink_match,
title=title,
note_types=note_types,
after_date=after_date,
search_item_types=search_item_types,
metadata_filters=metadata_filters,
)
# set limit and offset
params["limit"] = limit
params["offset"] = offset
sql = f"""
SELECT
search_index.project_id,
@@ -946,7 +904,7 @@ class PostgresSearchRepository(SearchRepositoryBase):
{score_expr} as score
FROM {from_clause}
WHERE {where_clause}
ORDER BY score DESC {order_by_clause}, search_index.id ASC
ORDER BY score DESC, search_index.id ASC {order_by_clause}
LIMIT :limit
OFFSET :offset
"""
@@ -957,7 +915,17 @@ class PostgresSearchRepository(SearchRepositoryBase):
result = await session.execute(text(sql), params)
rows = result.fetchall()
except Exception as e:
if self._is_tsquery_syntax_error(e):
# Handle tsquery syntax errors (and only those).
#
# Important: Postgres errors for other failures (e.g. missing table) will still mention
# `to_tsquery(...)` in the SQL text, so checking for the substring "tsquery" is too broad.
msg = str(e).lower()
if (
"syntax error in tsquery" in msg
or "invalid input syntax for type tsquery" in msg
or "no operand in tsquery" in msg
or "no operator in tsquery" in msg
):
logger.warning(f"tsquery syntax error for search term: {search_text}, error: {e}")
return []
@@ -998,60 +966,3 @@ class PostgresSearchRepository(SearchRepositoryBase):
)
return results
async def count(
self,
search_text: Optional[str] = None,
permalink: Optional[str] = None,
permalink_match: Optional[str] = None,
title: Optional[str] = None,
note_types: Optional[List[str]] = None,
after_date: Optional[datetime] = None,
search_item_types: Optional[List[SearchItemType]] = None,
metadata_filters: Optional[dict] = None,
retrieval_mode: SearchRetrievalMode = SearchRetrievalMode.FTS,
min_similarity: Optional[float] = None,
) -> int:
"""Count indexed content matching the Postgres FTS query."""
if retrieval_mode != SearchRetrievalMode.FTS:
return await super().count(
search_text=search_text,
permalink=permalink,
permalink_match=permalink_match,
title=title,
note_types=note_types,
after_date=after_date,
search_item_types=search_item_types,
metadata_filters=metadata_filters,
retrieval_mode=retrieval_mode,
min_similarity=min_similarity,
)
(
from_clause,
where_clause,
params,
_order_by_clause,
_score_expr,
) = await self._build_fts_query_parts(
search_text=search_text,
permalink=permalink,
permalink_match=permalink_match,
title=title,
note_types=note_types,
after_date=after_date,
search_item_types=search_item_types,
metadata_filters=metadata_filters,
)
sql = f"SELECT COUNT(*) FROM {from_clause} WHERE {where_clause}"
logger.trace(f"Count {sql} params: {params}")
try:
async with db.scoped_session(self.session_maker) as session:
result = await session.execute(text(sql), params)
return int(result.scalar_one())
except Exception as e:
if self._is_tsquery_syntax_error(e):
logger.warning(f"tsquery syntax error for search term: {search_text}, error: {e}")
return 0
logger.error(f"Database error during search count: {e}")
raise
@@ -4,9 +4,7 @@ from pathlib import Path
from typing import Optional, Sequence, Union
from loguru import logger
from sqlalchemy import inspect as sa_inspect, select, text
from sqlalchemy.exc import NoResultFound, OperationalError
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from basic_memory import db
@@ -14,65 +12,6 @@ from basic_memory.models.project import Project
from basic_memory.repository.repository import Repository
async def _load_sqlite_vec_on_session(session) -> bool:
"""Ensure the sqlite-vec extension is loaded on this session's connection.
Returns True when vec0 is available after the call. Returns False when the
extension can't be loaded on this Python build (e.g., python.org macOS or
Windows interpreters without `enable_load_extension`) every connection in
the pool shares the same interpreter, so a False here also means no
embedding row could ever have been written, and skipping the embeddings
purge is safe.
Mirrors SQLiteSearchRepository._ensure_sqlite_vec_loaded but as a free
function: we don't have a SearchRepository instance during project delete,
and the per-connection nature of extension loading means a pooled connection
routed to this session might not have vec loaded even when other
connections wrote embeddings.
"""
try:
await session.execute(text("SELECT vec_version()"))
return True
except OperationalError:
pass
try:
import sqlite_vec # type: ignore[import-not-found]
except ImportError:
logger.debug("sqlite-vec package not installed; skipping vec purge")
return False
async_connection = await session.connection()
raw_connection = await async_connection.get_raw_connection()
driver_connection = raw_connection.driver_connection
if not hasattr(driver_connection, "enable_load_extension"):
# Trigger: CPython build without sqlite extension support (#711).
# Why: load_extension is unavailable, so no connection in this pool
# can host vec0. No embeddings exist anywhere.
# Outcome: skip the embeddings purge entirely.
logger.debug(
"Skipping search_vector_embeddings purge: this Python build does "
"not support SQLite extension loading"
)
return False
try:
await driver_connection.enable_load_extension(True)
await driver_connection.load_extension(sqlite_vec.loadable_path())
await driver_connection.enable_load_extension(False)
await session.execute(text("SELECT vec_version()"))
except Exception as exc:
logger.warning(
"Failed to load sqlite-vec for project delete cleanup; "
"skipping embeddings purge: {}",
exc,
)
return False
return True
class ProjectRepository(Repository[Project]):
"""Repository for Project model.
@@ -182,83 +121,6 @@ class ProjectRepository(Repository[Project]):
return target_project
return None # pragma: no cover
async def delete(self, entity_id: int) -> bool:
"""Delete a project and its derived search rows in one transaction.
The cascade picture differs by backend:
- search_index project: Postgres has ON DELETE CASCADE FK; SQLite
stores search_index as an FTS5 virtual table and can't carry FKs,
so it needs explicit cleanup.
- search_vector_chunks project: neither backend has an FK here, so
both need an explicit DELETE.
- search_vector_embeddings search_vector_chunks: Postgres has an FK
(chunk_id REFERENCES ON DELETE CASCADE); SQLite stores embeddings
in a vec0 virtual table keyed by rowid with no cascade. On SQLite
the embeddings must be purged before the chunk rows, otherwise
`_run_vector_query` keeps returning stale vectors that crowd out
live results.
Each derived table is created lazily (search_index by
SearchRepository.init_search_index, the vector tables once semantic
search initializes), so any of them may be absent on minimal test DBs.
Inspect the connection once and skip whichever is missing.
"""
logger.debug(f"Deleting Project and search rows for project_id: {entity_id}")
async with db.scoped_session(self.session_maker) as session:
try:
result = await session.execute(
select(self.Model).filter(self.primary_key == entity_id)
)
project = result.scalars().one()
except NoResultFound:
logger.debug(f"No Project found to delete: {entity_id}")
return False
dialect_name = session.bind.dialect.name if session.bind else "sqlite"
is_sqlite = dialect_name == "sqlite"
existing_tables = await session.run_sync(
lambda sync_session: set(sa_inspect(sync_session.connection()).get_table_names())
)
# search_index: SQLite has no FK on the FTS5 virtual table; Postgres
# cascades from the project FK, so the explicit DELETE is redundant.
if is_sqlite and "search_index" in existing_tables:
await session.execute(
text("DELETE FROM search_index WHERE project_id = :project_id"),
{"project_id": entity_id},
)
# search_vector_chunks: no FK to project on either backend, so both
# backends need this. SQLite must purge vec0 embeddings first
# (rowid pseudocolumn — Postgres uses chunk_id and would 500 here);
# Postgres' chunk_id FK CASCADE handles its embeddings cleanup when
# we delete the chunk rows below.
if "search_vector_chunks" in existing_tables:
if is_sqlite and "search_vector_embeddings" in existing_tables:
# Extension loading is per-connection. We must load vec0 on
# *this* session before the DELETE; otherwise a different
# pooled connection might have written embeddings that we'd
# silently leave behind.
if await _load_sqlite_vec_on_session(session):
await session.execute(
text(
"DELETE FROM search_vector_embeddings WHERE rowid IN ("
"SELECT id FROM search_vector_chunks "
"WHERE project_id = :project_id)"
),
{"project_id": entity_id},
)
await session.execute(
text("DELETE FROM search_vector_chunks WHERE project_id = :project_id"),
{"project_id": entity_id},
)
await session.delete(project)
logger.debug(f"Deleted Project and search rows for project_id: {entity_id}")
return True
async def update_path(self, project_id: int, new_path: str) -> Optional[Project]:
"""Update project path.
@@ -50,22 +50,6 @@ class SearchRepository(Protocol):
"""Search across indexed content."""
...
async def count(
self,
search_text: Optional[str] = None,
permalink: Optional[str] = None,
permalink_match: Optional[str] = None,
title: Optional[str] = None,
note_types: Optional[List[str]] = None,
after_date: Optional[datetime] = None,
search_item_types: Optional[List[SearchItemType]] = None,
metadata_filters: Optional[dict] = None,
retrieval_mode: SearchRetrievalMode = SearchRetrievalMode.FTS,
min_similarity: Optional[float] = None,
) -> int:
"""Count indexed content matching the same filters as search."""
...
async def index_item(self, search_index_row: SearchIndexRow) -> None:
"""Index a single item."""
...
@@ -247,24 +247,6 @@ class SearchRepositoryBase(ABC):
"""
pass
async def count(
self,
search_text: Optional[str] = None,
permalink: Optional[str] = None,
permalink_match: Optional[str] = None,
title: Optional[str] = None,
note_types: Optional[List[str]] = None,
after_date: Optional[datetime] = None,
search_item_types: Optional[List[SearchItemType]] = None,
metadata_filters: Optional[Dict[str, Any]] = None,
retrieval_mode: SearchRetrievalMode = SearchRetrievalMode.FTS,
min_similarity: Optional[float] = None,
) -> int:
"""Count results when a backend-specific COUNT query is available."""
if retrieval_mode != SearchRetrievalMode.FTS:
raise ValueError("Exact counts are only supported for full-text search retrieval.")
raise NotImplementedError("Backend search repositories must implement full-text counts.")
# ------------------------------------------------------------------
# Abstract methods — semantic search (backend-specific DB operations)
# ------------------------------------------------------------------
@@ -94,22 +94,9 @@ class SQLiteSearchRepository(SearchRepositoryBase):
raise e
# Fail fast: create vector tables at startup so missing sqlite-vec
# or embedding provider errors surface immediately.
# Trigger: the runtime semantic stack (sqlite-vec extension or embedding
# provider) is unavailable at startup.
# Why: failing the whole MCP boot for a search-only feature blocks
# Claude Desktop's handshake (#711). Keyword-only search is a
# reasonable fallback while the user resolves the dependency.
# Outcome: log the cause, mark this repository as semantic-disabled so
# downstream calls short-circuit cleanly, and let init complete.
# or embedding provider errors surface immediately
if self._semantic_enabled:
try:
await self._ensure_vector_tables()
except SemanticDependenciesMissingError as exc:
logger.warning(
f"Semantic search disabled: {exc}. Falling back to keyword-only search."
)
self._semantic_enabled = False
await self._ensure_vector_tables()
# ------------------------------------------------------------------
# FTS5 query preparation (backend-specific)
@@ -387,25 +374,6 @@ class SQLiteSearchRepository(SearchRepositoryBase):
async_connection = await session.connection()
raw_connection = await async_connection.get_raw_connection()
driver_connection = raw_connection.driver_connection
# Trigger: the underlying CPython was built without sqlite extension support.
# Why: python.org's macOS installer ships a stripped sqlite3 module with no
# enable_load_extension; when uvx happens to pick that interpreter (#711),
# the AttributeError surfaces here and previously crashed startup before
# Claude Desktop could complete its MCP handshake.
# Outcome: convert to SemanticDependenciesMissingError so the init-time
# handler can degrade gracefully to keyword search instead of dying.
if not hasattr(driver_connection, "enable_load_extension"):
raise SemanticDependenciesMissingError(
"This Python build does not support SQLite extension loading "
"(no enable_load_extension on sqlite3.Connection). "
"Common cause: python.org Python on macOS. "
"Reinstall basic-memory under a Python that ships extension "
"support (uv-managed CPython, Homebrew Python, or the official "
"Docker image), or set semantic_search_enabled=false in config "
"to silence this and use keyword-only search."
)
await driver_connection.enable_load_extension(True)
await driver_connection.load_extension(sqlite_vec.loadable_path())
await driver_connection.enable_load_extension(False)
@@ -620,25 +588,6 @@ class SQLiteSearchRepository(SearchRepositoryBase):
)
await session.commit()
async def drop_vector_tables(self) -> None:
"""Drop SQLite vector tables on a sqlite-vec-enabled connection."""
async with db.scoped_session(self.session_maker) as session:
vector_sql_result = await session.execute(
text(
"SELECT sql FROM sqlite_master "
"WHERE type = 'table' AND name = 'search_vector_embeddings'"
)
)
vector_sql = vector_sql_result.scalar()
if vector_sql and "using vec0" in vector_sql.lower():
await self._ensure_sqlite_vec_loaded(session)
await session.execute(text("DROP TABLE IF EXISTS search_vector_embeddings"))
await session.execute(text("DROP TABLE IF EXISTS search_vector_chunks"))
await session.execute(text("DROP TABLE IF EXISTS search_vector_index"))
await session.commit()
self._vector_tables_initialized = False
async def delete_stale_vector_rows(self) -> None:
"""Delete vector rows whose source entities no longer exist."""
await self._ensure_vector_tables()
@@ -720,11 +669,7 @@ class SQLiteSearchRepository(SearchRepositoryBase):
# FTS search (backend-specific)
# ------------------------------------------------------------------
@staticmethod
def _is_fts5_syntax_error(exc: Exception) -> bool:
return "fts5: syntax error" in str(exc).lower()
async def _build_fts_query_parts(
async def search(
self,
search_text: Optional[str] = None,
permalink: Optional[str] = None,
@@ -734,8 +679,31 @@ class SQLiteSearchRepository(SearchRepositoryBase):
after_date: Optional[datetime] = None,
search_item_types: Optional[List[SearchItemType]] = None,
metadata_filters: Optional[dict] = None,
) -> tuple[str, str, dict, str]:
"""Build SQLite FTS FROM/WHERE params shared by search and count."""
retrieval_mode: SearchRetrievalMode = SearchRetrievalMode.FTS,
min_similarity: Optional[float] = None,
limit: int = 10,
offset: int = 0,
) -> List[SearchIndexRow]:
"""Search across all indexed content using SQLite FTS5."""
# --- Dispatch vector / hybrid modes (shared logic) ---
dispatched = await self._dispatch_retrieval_mode(
search_text=search_text,
permalink=permalink,
permalink_match=permalink_match,
title=title,
note_types=note_types,
after_date=after_date,
search_item_types=search_item_types,
metadata_filters=metadata_filters,
retrieval_mode=retrieval_mode,
min_similarity=min_similarity,
limit=limit,
offset=offset,
)
if dispatched is not None:
return dispatched
# --- FTS mode (SQLite-specific) ---
conditions = []
match_conditions = []
params = {}
@@ -808,8 +776,7 @@ class SQLiteSearchRepository(SearchRepositoryBase):
# Handle date filter using datetime() for proper comparison
if after_date:
params["after_date"] = after_date
# Filter on updated_at so recently-edited notes are included even when created_at is old
conditions.append("datetime(search_index.updated_at) > datetime(:after_date)")
conditions.append("datetime(search_index.created_at) > datetime(:after_date)")
# order by most recent first
order_by_clause = ", search_index.updated_at DESC"
@@ -912,60 +879,13 @@ class SQLiteSearchRepository(SearchRepositoryBase):
params["project_id"] = self.project_id
conditions.append("search_index.project_id = :project_id")
# Build WHERE clause
where_clause = " AND ".join(conditions) if conditions else "1=1"
return from_clause, where_clause, params, order_by_clause
async def search(
self,
search_text: Optional[str] = None,
permalink: Optional[str] = None,
permalink_match: Optional[str] = None,
title: Optional[str] = None,
note_types: Optional[List[str]] = None,
after_date: Optional[datetime] = None,
search_item_types: Optional[List[SearchItemType]] = None,
metadata_filters: Optional[dict] = None,
retrieval_mode: SearchRetrievalMode = SearchRetrievalMode.FTS,
min_similarity: Optional[float] = None,
limit: int = 10,
offset: int = 0,
) -> List[SearchIndexRow]:
"""Search across all indexed content using SQLite FTS5."""
# --- Dispatch vector / hybrid modes (shared logic) ---
dispatched = await self._dispatch_retrieval_mode(
search_text=search_text,
permalink=permalink,
permalink_match=permalink_match,
title=title,
note_types=note_types,
after_date=after_date,
search_item_types=search_item_types,
metadata_filters=metadata_filters,
retrieval_mode=retrieval_mode,
min_similarity=min_similarity,
limit=limit,
offset=offset,
)
if dispatched is not None:
return dispatched
# --- FTS mode (SQLite-specific) ---
from_clause, where_clause, params, order_by_clause = await self._build_fts_query_parts(
search_text=search_text,
permalink=permalink,
permalink_match=permalink_match,
title=title,
note_types=note_types,
after_date=after_date,
search_item_types=search_item_types,
metadata_filters=metadata_filters,
)
# set limit on search query
params["limit"] = limit
params["offset"] = offset
# Build WHERE clause
where_clause = " AND ".join(conditions) if conditions else "1=1"
sql = f"""
SELECT
search_index.project_id,
@@ -998,7 +918,7 @@ class SQLiteSearchRepository(SearchRepositoryBase):
rows = result.fetchall()
except Exception as e:
# Handle FTS5 syntax errors and provide user-friendly feedback
if self._is_fts5_syntax_error(e): # pragma: no cover
if "fts5: syntax error" in str(e).lower(): # pragma: no cover
logger.warning(f"FTS5 syntax error for search term: {search_text}, error: {e}")
# Return empty results rather than crashing
return []
@@ -1036,54 +956,3 @@ class SQLiteSearchRepository(SearchRepositoryBase):
)
return results
async def count(
self,
search_text: Optional[str] = None,
permalink: Optional[str] = None,
permalink_match: Optional[str] = None,
title: Optional[str] = None,
note_types: Optional[List[str]] = None,
after_date: Optional[datetime] = None,
search_item_types: Optional[List[SearchItemType]] = None,
metadata_filters: Optional[dict] = None,
retrieval_mode: SearchRetrievalMode = SearchRetrievalMode.FTS,
min_similarity: Optional[float] = None,
) -> int:
"""Count indexed content matching the SQLite FTS query."""
if retrieval_mode != SearchRetrievalMode.FTS:
return await super().count(
search_text=search_text,
permalink=permalink,
permalink_match=permalink_match,
title=title,
note_types=note_types,
after_date=after_date,
search_item_types=search_item_types,
metadata_filters=metadata_filters,
retrieval_mode=retrieval_mode,
min_similarity=min_similarity,
)
from_clause, where_clause, params, _order_by_clause = await self._build_fts_query_parts(
search_text=search_text,
permalink=permalink,
permalink_match=permalink_match,
title=title,
note_types=note_types,
after_date=after_date,
search_item_types=search_item_types,
metadata_filters=metadata_filters,
)
sql = f"SELECT COUNT(*) FROM {from_clause} WHERE {where_clause}"
logger.trace(f"Count {sql} params: {params}")
try:
async with db.scoped_session(self.session_maker) as session:
result = await session.execute(text(sql), params)
return int(result.scalar_one())
except Exception as e:
if self._is_fts5_syntax_error(e): # pragma: no cover
logger.warning(f"FTS5 syntax error for search term: {search_text}, error: {e}")
return 0
logger.error(f"Database error during search count: {e}")
raise
+20 -67
View File
@@ -8,9 +8,7 @@ Syntax reference:
field: type, description # required field
field?: type, description # optional field
field(array): type # array of values
field(array, description): type # array with description
field?(enum): [val1, val2] # enumeration
field?(enum, description): [val1, val2] # enum with description
field?(object): # nested object
sub_field: type
EntityName as type (capitalized) # entity reference
@@ -60,88 +58,46 @@ class SchemaDefinition:
# with an uppercase letter is treated as an entity reference.
SCALAR_TYPES = frozenset({"string", "integer", "number", "boolean", "any"})
MODIFIER_TYPES = frozenset({"array", "enum", "object"})
# --- Field Name Parsing ---
def _parse_field_key_parts(key: str) -> tuple[str, bool, bool, bool, bool, str | None]:
def _parse_field_key(key: str) -> tuple[str, bool, bool, bool, bool]:
"""Parse a Picoschema field key into its components.
Returns (name, required, is_array, is_enum, is_object, description).
The key format is: name[?][(array|enum|object[, description])]
Returns (name, required, is_array, is_enum, is_object).
The key format is: name[?][(array|enum|object)]
Examples:
"name" -> ("name", True, False, False, False, None)
"role?" -> ("role", False, False, False, False, None)
"tags?(array)" -> ("tags", False, True, False, False, None)
"tags?(array, labels)" -> ("tags", False, True, False, False, "labels")
"status?(enum)" -> ("status", False, False, True, False, None)
"metadata?(object)" -> ("metadata", False, False, False, True, None)
"name" -> ("name", True, False, False)
"role?" -> ("role", False, False, False)
"tags?(array)" -> ("tags", False, True, False)
"status?(enum)" -> ("status", False, False, True)
"metadata?(object)" -> ("metadata", False, False, False) + children
"""
required = True
is_array = False
is_enum = False
is_object = False
description = None
key, modifier, description = _split_modifier_suffix(key)
if modifier == "array":
# Check for modifier suffix: (array), (enum), (object)
if key.endswith("(array)"):
is_array = True
elif modifier == "enum":
key = key[: -len("(array)")]
elif key.endswith("(enum)"):
is_enum = True
elif modifier == "object":
key = key[: -len("(enum)")]
elif key.endswith("(object)"):
is_object = True
key = key[: -len("(object)")]
# Check for optional marker
if key.endswith("?"):
required = False
key = key[:-1]
return key.strip(), required, is_array, is_enum, is_object, description
def _parse_field_key(key: str) -> tuple[str, bool, bool, bool, bool]:
"""Parse a Picoschema field key, discarding any modifier description."""
name, required, is_array, is_enum, is_object, _description = _parse_field_key_parts(key)
return name, required, is_array, is_enum, is_object
def _split_modifier_suffix(key: str) -> tuple[str, str | None, str | None]:
"""Split a trailing picoschema modifier from a field key."""
stripped_key = key.rstrip()
if not stripped_key.endswith(")"):
return key, None, None
# Trigger: field names and modifier descriptions may both contain parentheses
# Why: only the parenthesis paired with the final suffix can introduce a modifier
# Outcome: preserves names like "risk(score)" and descriptions like "labels (freeform)"
open_paren_index = -1
depth = 0
for index in range(len(stripped_key) - 1, -1, -1):
char = stripped_key[index]
if char == ")":
depth += 1
elif char == "(":
depth -= 1
if depth == 0:
open_paren_index = index
break
if open_paren_index == -1:
return key, None, None
modifier_text = stripped_key[open_paren_index + 1 : -1].strip()
modifier, separator, description = modifier_text.partition(",")
modifier = modifier.strip()
if modifier not in MODIFIER_TYPES:
return key, None, None
key_without_modifier = stripped_key[:open_paren_index].rstrip()
parsed_description = description.strip() if separator else None
return key_without_modifier, modifier, parsed_description or None
return key, required, is_array, is_enum, is_object
def _parse_type_and_description(value: str) -> tuple[str, str | None]:
@@ -214,7 +170,7 @@ def parse_picoschema(yaml_dict: dict) -> list[SchemaField]:
fields: list[SchemaField] = []
for key, value in yaml_dict.items():
name, required, is_array, is_enum, is_object, key_description = _parse_field_key_parts(key)
name, required, is_array, is_enum, is_object = _parse_field_key(key)
# --- Enum fields ---
# Trigger: value is a list or a string containing bracketed enum values
@@ -223,12 +179,11 @@ def parse_picoschema(yaml_dict: dict) -> list[SchemaField]:
# in YAML to avoid parse errors)
# Outcome: SchemaField with is_enum=True and enum_values populated
if is_enum:
description = key_description
description = None
if isinstance(value, list):
enum_values = [str(v) for v in value]
else:
enum_values, value_description = _parse_enum_string(str(value))
description = description or value_description
enum_values, description = _parse_enum_string(str(value))
fields.append(
SchemaField(
name=name,
@@ -252,15 +207,13 @@ def parse_picoschema(yaml_dict: dict) -> list[SchemaField]:
name=name,
type="object",
required=required,
description=key_description,
children=children,
)
)
continue
# --- Scalar and entity ref fields ---
type_str, value_description = _parse_type_and_description(str(value))
description = key_description or value_description
type_str, description = _parse_type_and_description(str(value))
is_entity_ref = _is_entity_ref_type(type_str)
fields.append(
-45
View File
@@ -88,51 +88,6 @@ class WorkspaceListResponse(BaseModel):
)
def workspace_matches_exact_identifier(workspace: WorkspaceInfo, identifier: str) -> bool:
"""Return True when identifier matches workspace tenant_id, slug, or name."""
if workspace.tenant_id == identifier:
return True
if workspace.slug.casefold() == identifier.casefold():
return True
return workspace.name.casefold() == identifier.casefold()
def workspace_matches_identifier(workspace: WorkspaceInfo, identifier: str) -> bool:
"""Return True when identifier matches workspace tenant_id, slug, name, or type."""
return (
workspace_matches_exact_identifier(workspace, identifier)
or workspace.workspace_type.casefold() == identifier.casefold()
)
def format_workspace_choices(workspaces: list[WorkspaceInfo]) -> str:
"""Format deterministic workspace choices for prompt-style errors."""
return "\n".join(
[
(
f"- {item.name} "
f"(slug={item.slug}, type={item.workspace_type}, "
f"role={item.role}, tenant_id={item.tenant_id})"
)
for item in workspaces
]
)
def format_workspace_selection_choices(workspaces: list[WorkspaceInfo]) -> str:
"""Format matching workspaces with copyable unique identifiers first."""
return "\n".join(
[
(
f"- {item.name} ({item.workspace_type}, role={item.role})\n"
f" workspace: {item.slug}\n"
f" tenant_id: {item.tenant_id}"
)
for item in workspaces
]
)
class CloudProjectIndexStatus(BaseModel):
"""Index freshness summary for one cloud project."""
-1
View File
@@ -142,5 +142,4 @@ class SearchResponse(BaseModel):
results: List[SearchResult]
current_page: int
page_size: int
total: int = 0
has_more: bool = False
+1 -1
View File
@@ -5,7 +5,7 @@ from typing import TYPE_CHECKING, Dict, List, Set
from pydantic import BaseModel, Field
# avoid circular imports
# avoid cirular imports
if TYPE_CHECKING: # pragma: no cover
from basic_memory.sync.sync_service import SyncReport
+4 -4
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any, List, Optional, Tuple, TYPE_CHECKING
from typing import List, Optional, Tuple, TYPE_CHECKING
from loguru import logger
@@ -307,7 +307,7 @@ class ContextService:
entity_id_values = ", ".join([str(i) for i in entity_ids])
# Parameters for bindings - include project_id for security filtering
params: dict[str, Any] = {
params = {
"max_depth": max_depth,
"max_results": max_results,
"project_id": self.search_repository.project_id,
@@ -322,9 +322,9 @@ class ContextService:
since_utc = (
since.astimezone(timezone.utc) if since.tzinfo else since
) # pragma: no cover
params["since_date"] = since_utc.replace(tzinfo=None) # pragma: no cover
params["since_date"] = since_utc.replace(tzinfo=None) # pyright: ignore # pragma: no cover
else:
params["since_date"] = since.isoformat()
params["since_date"] = since.isoformat() # pyright: ignore
date_filter = "AND e.created_at >= :since_date"
relation_date_filter = "AND e_from.created_at >= :since_date"
timeframe_condition = "AND eg.relation_date >= :since_date"
+8 -14
View File
@@ -48,7 +48,6 @@ from basic_memory.services.exceptions import (
from basic_memory.services.link_resolver import LinkResolver
from basic_memory.services.search_service import SearchService
from basic_memory.utils import build_canonical_permalink
from basic_memory.workspace_context import workspace_slug_for_canonical_permalinks
@dataclass(frozen=True)
@@ -206,20 +205,15 @@ class EntityService(BaseService[EntityModel]):
if self.app_config:
include_project = self.app_config.permalinks_include_project
workspace_permalink = workspace_slug_for_canonical_permalinks()
project_permalink = None
# Trigger: project-prefixed permalinks are enabled, or organization workspace
# context requires a complete workspace/project canonical permalink.
# Why: project slug is the stable middle segment for globally addressable links.
# Outcome: fetch and cache the project's permalink before building the canonical URL.
if include_project or workspace_permalink:
# Trigger: project-prefixed permalinks are enabled
# Why: we need the project slug to build the canonical permalink
# Outcome: fetch and cache the project's permalink
if include_project:
project_permalink = await self._get_project_permalink()
desired_permalink = build_canonical_permalink(
project_permalink,
file_path_str,
include_project=include_project,
workspace_permalink=workspace_permalink,
project_permalink, file_path_str, include_project=include_project
)
# Make unique if needed - enhanced to handle character conflicts
@@ -1042,9 +1036,9 @@ class EntityService(BaseService[EntityModel]):
for rel, resolved in zip(markdown.relations, resolved_entities):
# Handle exceptions from gather and None results
target_entity: Optional[Entity] = None
if not isinstance(resolved, BaseException):
# asyncio.gather(..., return_exceptions=True) can return any BaseException.
target_entity = resolved
if not isinstance(resolved, Exception):
# Type narrowing: resolved is Optional[Entity] here, not Exception
target_entity = resolved # pyright: ignore [reportAssignmentType]
if target_entity is None and not resolve_targets:
target_entity = await self._resolve_deferred_self_relation(rel.target, entity)
+21 -70
View File
@@ -1,7 +1,7 @@
"""Service and helpers for resolving markdown links and permalink-like identifiers."""
"""Service for resolving markdown links to permalinks."""
import uuid as uuid_mod
from typing import Any, Optional, Tuple, Dict
from typing import Optional, Tuple, Dict
from loguru import logger
@@ -13,59 +13,10 @@ from basic_memory.repository.search_repository import create_search_repository
from basic_memory.schemas.search import SearchQuery, SearchItemType
from basic_memory.services.search_service import SearchService
from basic_memory.utils import (
build_permalink_resolution_candidates,
build_canonical_permalink,
generate_permalink,
normalize_project_reference,
)
from basic_memory.workspace_context import current_workspace_permalink_context
def is_workspace_qualified_plain_identifier(identifier: str) -> bool:
"""Return True for plain ``<workspace>/<project>/<path>`` identifiers."""
stripped = identifier.strip()
if stripped.startswith("memory://"):
return False
normalized = normalize_project_reference(stripped).strip("/")
return len(normalized.split("/", 2)) == 3
async def detect_project_from_workspace_identifier_prefix(
identifier: str,
config: BasicMemoryConfig,
context: Any | None = None,
) -> Optional[str]:
"""Resolve a project route from a plain workspace-qualified identifier."""
if not is_workspace_qualified_plain_identifier(identifier):
return None
from basic_memory.mcp.project_context import (
_workspace_identifier_discovery_available,
resolve_workspace_qualified_identifier,
)
if not _workspace_identifier_discovery_available(identifier, config):
return None
workspace_discovery_fallback_errors = (
"not found",
"no accessible workspaces",
"unable to discover",
)
try:
workspace_resolution = await resolve_workspace_qualified_identifier(
identifier,
context=context,
)
except ValueError as exc:
message = str(exc).lower()
if any(error in message for error in workspace_discovery_fallback_errors):
return None
raise
if workspace_resolution is None:
return None
return workspace_resolution.project_identifier
class LinkResolver:
@@ -238,25 +189,25 @@ class LinkResolver:
"""Resolve a link within a specific project scope."""
clean_text = link_text
include_project = self._include_project_permalinks()
workspace_context = current_workspace_permalink_context()
workspace_permalink = (
workspace_context.workspace_slug
if workspace_context and workspace_context.should_prefix_permalinks
else None
)
# Trigger: callers can pass title, short permalink, project/path, or
# workspace/project/path identifiers to the same resolver.
# Why: search results and memory:// URLs should stay usable across read,
# edit, delete, move, and API-level entity resolution.
# Outcome: resolve canonical workspace IDs and legacy project-prefixed rows
# through one shared candidate builder.
permalink_candidates = build_permalink_resolution_candidates(
clean_text,
project_permalink,
include_project=include_project,
workspace_permalink=workspace_permalink,
)
canonical_permalink: Optional[str] = None
legacy_permalink: Optional[str] = None
# Trigger: permalinks include project slug and project permalink is known
# Why: support globally addressable permalinks while keeping legacy links resolvable
# Outcome: include canonical and legacy candidates for resolution
if include_project and project_permalink:
canonical_permalink = build_canonical_permalink(
project_permalink, clean_text, include_project=True
)
if clean_text.startswith(f"{project_permalink}/"):
legacy_candidate = clean_text.removeprefix(f"{project_permalink}/")
if legacy_candidate:
legacy_permalink = legacy_candidate
permalink_candidates = []
for candidate in (clean_text, canonical_permalink, legacy_permalink):
if candidate and candidate not in permalink_candidates:
permalink_candidates.append(candidate)
# --- Path Resolution ---
# Note: All paths in Basic Memory are stored as POSIX strings (forward slashes)
+68 -189
View File
@@ -3,7 +3,6 @@
import asyncio
import ast
import re
from dataclasses import dataclass
from datetime import datetime
from typing import List, Optional, Set, Dict, Any
@@ -65,22 +64,6 @@ FTS_RELAXED_STOPWORDS = {
}
@dataclass(frozen=True)
class _PreparedSearchQuery:
"""Normalized query inputs shared by search and count."""
search_text: str | None
permalink: str | None
permalink_match: str | None
title: str | None
note_types: list[str] | None
search_item_types: list[SearchItemType] | None
after_date: datetime | None
metadata_filters: dict[str, Any] | None
retrieval_mode: SearchRetrievalMode
min_similarity: float | None
def _strip_nul(value: str) -> str:
"""Strip NUL bytes that PostgreSQL text columns cannot store.
@@ -126,23 +109,19 @@ class SearchService:
async def reindex_all(self, background_tasks: Optional[BackgroundTasks] = None) -> None:
"""Reindex all content from database."""
from basic_memory.repository.sqlite_search_repository import SQLiteSearchRepository
logger.info("Starting full reindex")
# Clear and recreate search index
await self.repository.execute_query(text("DROP TABLE IF EXISTS search_index"), params={})
if isinstance(self.repository, SQLiteSearchRepository):
await self.repository.drop_vector_tables()
else:
await self.repository.execute_query(
text("DROP TABLE IF EXISTS search_vector_embeddings"), params={}
)
await self.repository.execute_query(
text("DROP TABLE IF EXISTS search_vector_chunks"), params={}
)
await self.repository.execute_query(
text("DROP TABLE IF EXISTS search_vector_index"), params={}
)
await self.repository.execute_query(
text("DROP TABLE IF EXISTS search_vector_embeddings"), params={}
)
await self.repository.execute_query(
text("DROP TABLE IF EXISTS search_vector_chunks"), params={}
)
await self.repository.execute_query(
text("DROP TABLE IF EXISTS search_vector_index"), params={}
)
await self.init_search_index()
# Reindex all entities
@@ -153,20 +132,27 @@ class SearchService:
logger.info("Reindex complete")
def _prepare_query(self, query: SearchQuery) -> _PreparedSearchQuery | None:
"""Normalize a SearchQuery into repository arguments."""
search_text = query.text
tags = query.tags
async def search(self, query: SearchQuery, limit=10, offset=0) -> List[SearchIndexRow]:
"""Search across all indexed content.
# Support tag:<tag> shorthand by mapping to tags filter.
if search_text is not None:
search_text = search_text.strip() or None
if search_text and search_text.lower().startswith("tag:"):
tag_values = re.split(r"[,\s]+", search_text[4:].strip())
parsed_tags = [t for t in tag_values if t]
if parsed_tags:
tags = parsed_tags
search_text = None
Supports three modes:
1. Exact permalink: finds direct matches for a specific path
2. Pattern match: handles * wildcards in paths
3. Text search: full-text search across title/content
"""
# Support tag:<tag> shorthand by mapping to tags filter
if query.text:
text = query.text.strip()
if text.lower().startswith("tag:"):
tag_values = re.split(r"[,\s]+", text[4:].strip())
tags = [t for t in tag_values if t]
if tags:
query.tags = tags
query.text = None
if query.no_criteria():
logger.debug("no criteria passed to query")
return []
after_date = (
(
@@ -178,124 +164,50 @@ class SearchService:
else None
)
# Merge structured metadata filters (explicit + convenience fields).
# Merge structured metadata filters (explicit + convenience fields)
metadata_filters: Optional[Dict[str, Any]] = None
if query.metadata_filters or tags or query.status:
if query.metadata_filters or query.tags or query.status:
metadata_filters = dict(query.metadata_filters or {})
if tags:
metadata_filters.setdefault("tags", tags)
if query.tags:
metadata_filters.setdefault("tags", query.tags)
if query.status:
metadata_filters.setdefault("status", query.status)
prepared = _PreparedSearchQuery(
search_text=search_text,
permalink=query.permalink,
permalink_match=query.permalink_match,
title=query.title,
note_types=query.note_types,
search_item_types=query.entity_types,
after_date=after_date,
metadata_filters=metadata_filters,
retrieval_mode=query.retrieval_mode or SearchRetrievalMode.FTS,
min_similarity=query.min_similarity,
)
has_criteria = bool(
prepared.search_text
or prepared.permalink
or prepared.permalink_match
or prepared.title
or prepared.note_types
or prepared.search_item_types
or prepared.after_date
or prepared.metadata_filters
)
if not has_criteria:
logger.debug("no criteria passed to query")
return None
return prepared
@staticmethod
def _prepared_has_filters(prepared: _PreparedSearchQuery) -> bool:
return bool(
prepared.metadata_filters
or prepared.note_types
or prepared.search_item_types
or prepared.after_date
)
async def _search_repository(
self,
prepared: _PreparedSearchQuery,
*,
search_text: str | None,
limit: int,
offset: int,
) -> List[SearchIndexRow]:
return await self.repository.search(
search_text=search_text,
permalink=prepared.permalink,
permalink_match=prepared.permalink_match,
title=prepared.title,
note_types=prepared.note_types,
search_item_types=prepared.search_item_types,
after_date=prepared.after_date,
metadata_filters=prepared.metadata_filters,
retrieval_mode=prepared.retrieval_mode,
min_similarity=prepared.min_similarity,
limit=limit,
offset=offset,
)
async def _count_repository(
self,
prepared: _PreparedSearchQuery,
*,
search_text: str | None,
) -> int:
return await self.repository.count(
search_text=search_text,
permalink=prepared.permalink,
permalink_match=prepared.permalink_match,
title=prepared.title,
note_types=prepared.note_types,
search_item_types=prepared.search_item_types,
after_date=prepared.after_date,
metadata_filters=prepared.metadata_filters,
retrieval_mode=prepared.retrieval_mode,
min_similarity=prepared.min_similarity,
)
async def search(self, query: SearchQuery, limit=10, offset=0) -> List[SearchIndexRow]:
"""Search across all indexed content.
Supports three modes:
1. Exact permalink: finds direct matches for a specific path
2. Pattern match: handles * wildcards in paths
3. Text search: full-text search across title/content
"""
prepared = self._prepare_query(query)
if prepared is None:
return []
strict_search_text = prepared.search_text
retrieval_mode = query.retrieval_mode or SearchRetrievalMode.FTS
strict_search_text = query.text
has_query = bool(
strict_search_text or prepared.title or prepared.permalink or prepared.permalink_match
strict_search_text or query.title or query.permalink or query.permalink_match
)
has_filters = bool(
metadata_filters
or query.note_types
or query.entity_types
or after_date
or query.tags
or query.status
)
has_filters = self._prepared_has_filters(prepared)
with logfire.span(
"search.execute",
retrieval_mode=prepared.retrieval_mode.value,
retrieval_mode=retrieval_mode.value,
has_query=has_query,
has_filters=has_filters,
limit=limit,
offset=offset,
):
logger.trace(f"Searching with query: {query}")
results = await self._search_repository(
prepared,
# First pass: preserve existing strict search behavior.
results = await self.repository.search(
search_text=strict_search_text,
permalink=query.permalink,
permalink_match=query.permalink_match,
title=query.title,
note_types=query.note_types,
search_item_types=query.entity_types,
after_date=after_date,
metadata_filters=metadata_filters,
retrieval_mode=retrieval_mode,
min_similarity=query.min_similarity,
limit=limit,
offset=offset,
)
@@ -305,9 +217,7 @@ class SearchService:
# Outcome: retry once with relaxed OR terms while preserving explicit boolean intent.
if results:
return results
if not self._is_relaxed_fts_fallback_eligible(
query, strict_search_text, prepared.retrieval_mode
):
if not self._is_relaxed_fts_fallback_eligible(query, strict_search_text, retrieval_mode):
return results
assert strict_search_text is not None
@@ -321,57 +231,26 @@ class SearchService:
)
with logfire.span(
"search.relaxed_fts_retry",
retrieval_mode=prepared.retrieval_mode.value,
retrieval_mode=retrieval_mode.value,
token_count=len(self._tokenize_fts_text(strict_search_text)),
limit=limit,
offset=offset,
):
return await self._search_repository(
prepared,
return await self.repository.search(
search_text=relaxed_search_text,
permalink=query.permalink,
permalink_match=query.permalink_match,
title=query.title,
note_types=query.note_types,
search_item_types=query.entity_types,
after_date=after_date,
metadata_filters=metadata_filters,
retrieval_mode=retrieval_mode,
min_similarity=query.min_similarity,
limit=limit,
offset=offset,
)
async def count(self, query: SearchQuery) -> int:
"""Count all indexed rows matching a query."""
prepared = self._prepare_query(query)
if prepared is None:
return 0
strict_search_text = prepared.search_text
has_query = bool(
strict_search_text or prepared.title or prepared.permalink or prepared.permalink_match
)
has_filters = self._prepared_has_filters(prepared)
with logfire.span(
"search.count",
retrieval_mode=prepared.retrieval_mode.value,
has_query=has_query,
has_filters=has_filters,
):
total = await self._count_repository(prepared, search_text=strict_search_text)
if total > 0:
return total
if not self._is_relaxed_fts_fallback_eligible(
query, strict_search_text, prepared.retrieval_mode
):
return total
assert strict_search_text is not None
relaxed_search_text = self._build_relaxed_fts_query(strict_search_text)
if relaxed_search_text == strict_search_text:
return total
with logfire.span(
"search.count.relaxed_fts_retry",
retrieval_mode=prepared.retrieval_mode.value,
token_count=len(self._tokenize_fts_text(strict_search_text)),
):
return await self._count_repository(prepared, search_text=relaxed_search_text)
@staticmethod
def _tokenize_fts_text(search_text: str) -> list[str]:
"""Tokenize text into alphanumeric terms for relaxed FTS fallback."""
+6 -38
View File
@@ -1530,36 +1530,12 @@ class SyncService:
count += 1
return count
# Trigger: large-project scan optimization needs the OS `find` command.
# Why: passing argv directly avoids shell interpretation of configured project paths.
# Outcome: quotes and shell metacharacters in paths are treated as data.
process = await asyncio.create_subprocess_exec(
"find",
str(directory),
"-type",
"f",
"-print0",
process = await asyncio.create_subprocess_shell(
f'find "{directory}" -type f | wc -l',
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
count = 0
stderr_task = None
if process.stderr is not None:
stderr_task = asyncio.create_task(process.stderr.read())
if process.stdout is None:
await process.wait()
else:
# Trigger: `find` can emit one path per file for very large projects.
# Why: collecting every path via communicate() scales memory with path bytes.
# Outcome: count null-delimited records in fixed-size chunks.
while chunk := await process.stdout.read(1024 * 1024):
count += chunk.count(b"\0")
await process.wait()
stderr = await stderr_task if stderr_task is not None else b""
stdout, stderr = await process.communicate()
if process.returncode != 0:
error_msg = stderr.decode().strip()
@@ -1574,7 +1550,7 @@ class SyncService:
count += 1
return count
return count
return int(stdout.strip())
async def _scan_directory_modified_since(
self, directory: Path, since_timestamp: float
@@ -1607,16 +1583,8 @@ class SyncService:
# Convert timestamp to find-compatible format
since_date = datetime.fromtimestamp(since_timestamp).strftime("%Y-%m-%d %H:%M:%S")
# Trigger: incremental scans ask `find` to filter by modification time.
# Why: passing argv directly avoids shell interpretation of paths and timestamps.
# Outcome: optimized scanning keeps its speed without a shell injection boundary.
process = await asyncio.create_subprocess_exec(
"find",
str(directory),
"-type",
"f",
"-newermt",
since_date,
process = await asyncio.create_subprocess_shell(
f'find "{directory}" -type f -newermt "{since_date}"',
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
+33 -75
View File
@@ -93,7 +93,6 @@ class WatchService:
self.status_path = app_config.data_dir_path / WATCH_STATUS_JSON
self.status_path.parent.mkdir(parents=True, exist_ok=True)
self._ignore_patterns_cache: dict[Path, Set[str]] = {}
self._sorted_watch_filter_roots: tuple[Path, ...] | None = None
self._sync_service_factory = sync_service_factory
# When set (typically from BASIC_MEMORY_MCP_PROJECT), the watch cycle
# only observes this project. Without it, each `basic-memory mcp --project X`
@@ -127,54 +126,41 @@ class WatchService:
async def _watch_projects_cycle(self, projects: Sequence[Project], stop_event: asyncio.Event):
"""Run one cycle of watching the given projects until stop_event is set."""
project_paths = [project.path for project in projects]
previous_filter_roots = self._sorted_watch_filter_roots
self._sorted_watch_filter_roots = tuple(
sorted(
(Path(project.path).expanduser().resolve() for project in projects),
# Trigger: configured project roots can overlap.
# Why: an enclosing project's hidden directory should still hide descendants.
# Outcome: choose the outermost matching root when checking hidden path parts.
key=lambda project_path: len(project_path.parts),
)
)
try:
async for changes in awatch(
*project_paths,
debounce=self.app_config.sync_delay,
watch_filter=self.filter_changes,
recursive=True,
stop_event=stop_event,
):
# group changes by project and filter using ignore patterns
project_changes = defaultdict(list)
for change, path in changes:
for project in projects:
if self.is_project_path(project, path):
# Check if the file should be ignored based on gitignore patterns
project_path = Path(project.path)
file_path = Path(path)
ignore_patterns = self._get_ignore_patterns(project_path)
async for changes in awatch(
*project_paths,
debounce=self.app_config.sync_delay,
watch_filter=self.filter_changes,
recursive=True,
stop_event=stop_event,
):
# group changes by project and filter using ignore patterns
project_changes = defaultdict(list)
for change, path in changes:
for project in projects:
if self.is_project_path(project, path):
# Check if the file should be ignored based on gitignore patterns
project_path = Path(project.path)
file_path = Path(path)
ignore_patterns = self._get_ignore_patterns(project_path)
if should_ignore_path(file_path, project_path, ignore_patterns):
logger.trace(
f"Ignoring watched file change: {file_path.relative_to(project_path)}"
)
continue
if should_ignore_path(file_path, project_path, ignore_patterns):
logger.trace(
f"Ignoring watched file change: {file_path.relative_to(project_path)}"
)
continue
project_changes[project].append((change, path))
break
project_changes[project].append((change, path))
break
# create coroutines to handle changes
change_handlers = [
self.handle_changes(project, set(changes))
for project, changes in project_changes.items()
]
# create coroutines to handle changes
change_handlers = [
self.handle_changes(project, set(changes))
for project, changes in project_changes.items()
]
# process changes
await asyncio.gather(*change_handlers)
finally:
self._sorted_watch_filter_roots = previous_filter_roots
# process changes
await asyncio.gather(*change_handlers)
async def _select_projects_to_watch(self) -> list[Project]:
"""Return the set of projects this watch cycle should observe.
@@ -281,43 +267,15 @@ class WatchService:
self.state.running = False
await self.write_status()
def filter_changes(self, change: Change, path: str) -> bool:
def filter_changes(self, change: Change, path: str) -> bool: # pragma: no cover
"""Filter to only watch non-hidden files and directories.
Returns:
True if the file should be watched, False if it should be ignored
"""
path_obj = Path(path).expanduser().resolve()
project_paths = self._sorted_watch_filter_roots
if project_paths is None:
project_paths = tuple(
sorted(
(
Path(entry.path).expanduser().resolve()
for entry in self.app_config.projects.values()
if entry.path
),
# Trigger: direct callers may not run inside a watch cycle.
# Why: tests and one-off calls still need the same hidden-path semantics.
# Outcome: compute the stable outermost-first order only for fallback calls.
key=lambda project_path: len(project_path.parts),
)
)
relative_path = None
for project_path in project_paths:
try:
relative_path = path_obj.relative_to(project_path)
break
except ValueError:
continue
# Trigger: a project may live under a hidden parent such as ~/.claude.
# Why: only dotfiles and dot-directories inside the watched project should be ignored.
# Outcome: hidden parents outside the project root do not mute legitimate project changes.
path_parts = relative_path.parts if relative_path is not None else path_obj.parts
# Skip hidden directories and files
path_parts = Path(path).parts
for part in path_parts:
if part.startswith("."):
return False
+1 -159
View File
@@ -224,43 +224,18 @@ def build_canonical_permalink(
project_permalink: Optional[str],
file_path: Union[Path, str, PathLike],
include_project: bool = True,
*,
workspace_permalink: Optional[str] = None,
) -> str:
"""Build a canonical permalink, optionally prefixed with workspace/project slugs.
"""Build a canonical permalink, optionally prefixed with project slug.
Args:
project_permalink: URL-friendly project identifier (slug). If None, no prefix is added.
file_path: Original file path or permalink-like string.
include_project: When True, prefix with project slug.
workspace_permalink: Optional URL-friendly workspace identifier. When provided,
prefix the project-qualified permalink with this workspace slug.
Returns:
Canonical permalink string.
"""
normalized_path = generate_permalink(file_path)
normalized_workspace = generate_permalink(workspace_permalink) if workspace_permalink else None
if normalized_workspace:
if not project_permalink:
raise ValueError("workspace_permalink requires project_permalink")
normalized_project = generate_permalink(project_permalink)
workspace_project_prefix = f"{normalized_workspace}/{normalized_project}"
if normalized_path == workspace_project_prefix or normalized_path.startswith(
f"{workspace_project_prefix}/"
):
return normalized_path
if normalized_path == normalized_project or normalized_path.startswith(
f"{normalized_project}/"
):
project_path = normalized_path
else:
project_path = f"{normalized_project}/{normalized_path}"
return f"{normalized_workspace}/{project_path}"
if not include_project or not project_permalink:
return normalized_path
@@ -269,144 +244,11 @@ def build_canonical_permalink(
if normalized_path == normalized_project or normalized_path.startswith(
f"{normalized_project}/"
):
project_path = normalized_path
else:
project_path = f"{normalized_project}/{normalized_path}"
return project_path
def build_qualified_permalink_reference(
project_permalink: Optional[str],
identifier: Union[Path, str, PathLike],
include_project: bool = True,
*,
workspace_permalink: Optional[str] = None,
) -> str:
"""Add workspace/project route prefixes while preserving lookup syntax.
Unlike ``build_canonical_permalink()``, this helper does not run the identifier
through permalink generation. It is for inbound references that may contain
lookup-only syntax such as ``.md`` extensions or ``*`` glob patterns.
"""
normalized_path = normalize_project_reference(str(identifier)).strip("/")
normalized_workspace = generate_permalink(workspace_permalink) if workspace_permalink else None
normalized_project = generate_permalink(project_permalink) if project_permalink else None
if normalized_workspace:
if not normalized_project:
raise ValueError("workspace_permalink requires project_permalink")
workspace_project_prefix = f"{normalized_workspace}/{normalized_project}"
if not normalized_path:
return workspace_project_prefix
if normalized_path == workspace_project_prefix or normalized_path.startswith(
f"{workspace_project_prefix}/"
):
return normalized_path
if normalized_path == normalized_project or normalized_path.startswith(
f"{normalized_project}/"
):
return f"{normalized_workspace}/{normalized_path}"
return f"{workspace_project_prefix}/{normalized_path}"
if not include_project or not normalized_project:
return normalized_path
if not normalized_path:
return normalized_project
if normalized_path == normalized_project or normalized_path.startswith(
f"{normalized_project}/"
):
return normalized_path
return f"{normalized_project}/{normalized_path}"
def build_permalink_resolution_candidates(
identifier: Union[Path, str, PathLike],
project_permalink: Optional[str],
include_project: bool = True,
*,
workspace_permalink: Optional[str] = None,
) -> list[str]:
"""Return permalink candidates from most caller-specific to broadest legacy form.
The first candidate preserves the normalized identifier the caller supplied. Follow-up
candidates add the active workspace/project route and legacy project/path forms so
all resolver callers share the same compatibility behavior.
"""
exact_path = normalize_project_reference(str(identifier)).strip("/")
normalized_path = generate_permalink(exact_path).strip("/")
normalized_project = generate_permalink(project_permalink) if project_permalink else None
normalized_workspace = generate_permalink(workspace_permalink) if workspace_permalink else None
candidates: list[str] = []
def add_candidate(value: str | None) -> None:
if value and value not in candidates:
candidates.append(value)
add_candidate(exact_path)
add_candidate(normalized_path)
if not normalized_project:
return candidates
workspace_project_prefix = (
f"{normalized_workspace}/{normalized_project}" if normalized_workspace else None
)
workspace_qualified = False
if workspace_project_prefix:
add_candidate(
build_canonical_permalink(
normalized_project,
normalized_path,
include_project=include_project,
workspace_permalink=normalized_workspace,
)
)
if normalized_path == workspace_project_prefix:
workspace_qualified = True
add_candidate(normalized_project)
elif normalized_path.startswith(f"{workspace_project_prefix}/"):
workspace_qualified = True
remainder = normalized_path.removeprefix(f"{workspace_project_prefix}/")
add_candidate(f"{normalized_project}/{remainder}")
add_candidate(remainder)
if workspace_project_prefix and not include_project and not workspace_qualified:
# Trigger: short lookup in a workspace where new canonical links omit project prefixes.
# Why: older rows in that same workspace may still be stored as `project/path`.
# Outcome: try the project-prefixed legacy form after the workspace-qualified form.
add_candidate(
build_canonical_permalink(
normalized_project,
normalized_path,
include_project=True,
)
)
if include_project and not workspace_qualified:
add_candidate(
build_canonical_permalink(
normalized_project,
normalized_path,
include_project=True,
)
)
if normalized_path == normalized_project:
return candidates
if normalized_path.startswith(f"{normalized_project}/"):
remainder = normalized_path.removeprefix(f"{normalized_project}/")
add_candidate(remainder)
if not include_project and normalized_path.startswith(f"{normalized_project}/"):
# Trigger: caller supplied `project/path` while legacy short permalinks are stored.
# Why: routing uses the project prefix, but strict lookup still needs the short row.
# Outcome: try `path` after the exact project-qualified candidate.
add_candidate(normalized_path.removeprefix(f"{normalized_project}/"))
return candidates
def setup_logging(
log_level: str = "INFO",
log_to_file: bool = False,
-114
View File
@@ -1,114 +0,0 @@
"""Request-local workspace context for canonical permalink generation."""
import re
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
from typing import Iterator
WORKSPACE_SLUG_HEADER = "X-Basic-Memory-Workspace-Slug"
WORKSPACE_TYPE_HEADER = "X-Basic-Memory-Workspace-Type"
_WORKSPACE_SLUG_PATTERN = re.compile(r"^[a-z0-9_-]+$")
_WORKSPACE_TYPES = {"personal", "organization"}
@dataclass(frozen=True)
class WorkspacePermalinkContext:
"""Workspace metadata needed to build canonical workspace permalinks."""
workspace_slug: str
workspace_type: str
@property
def should_prefix_permalinks(self) -> bool:
return bool(self.workspace_slug)
_workspace_permalink_context: ContextVar[WorkspacePermalinkContext | None] = ContextVar(
"basic_memory_workspace_permalink_context",
default=None,
)
def current_workspace_permalink_context() -> WorkspacePermalinkContext | None:
"""Return the active workspace permalink context, when one is set."""
return _workspace_permalink_context.get()
def validate_workspace_permalink_context_values(
workspace_slug: str | None,
workspace_type: str | None,
) -> None:
"""Validate workspace permalink metadata before it can affect stored permalinks."""
validation_error = workspace_permalink_context_validation_error(workspace_slug, workspace_type)
if validation_error is not None:
raise ValueError(validation_error)
def workspace_permalink_context_validation_error(
workspace_slug: str | None,
workspace_type: str | None,
) -> str | None:
"""Return the validation error for workspace permalink metadata, if any."""
if bool(workspace_slug) != bool(workspace_type):
return "workspace_slug and workspace_type must be provided together"
if not workspace_slug or not workspace_type:
return None
if _WORKSPACE_SLUG_PATTERN.fullmatch(workspace_slug) is None:
return f"{WORKSPACE_SLUG_HEADER} must match [a-z0-9_-]+"
if workspace_type not in _WORKSPACE_TYPES:
allowed = ", ".join(sorted(_WORKSPACE_TYPES))
return f"{WORKSPACE_TYPE_HEADER} must be one of: {allowed}"
return None
@contextmanager
def workspace_permalink_context(
workspace_slug: str | None,
workspace_type: str | None,
) -> Iterator[None]:
"""Set request-local workspace permalink metadata.
Cloud can populate this per request without storing workspace metadata in
local project config. The slug/type pair is all permalink generation needs.
"""
validate_workspace_permalink_context_values(workspace_slug, workspace_type)
if not workspace_slug or not workspace_type:
yield
return
token = _workspace_permalink_context.set(
WorkspacePermalinkContext(
workspace_slug=workspace_slug,
workspace_type=workspace_type,
)
)
try:
yield
finally:
_workspace_permalink_context.reset(token)
def workspace_permalink_headers() -> dict[str, str]:
"""Return HTTP headers for forwarding workspace permalink context."""
context = current_workspace_permalink_context()
if context is None:
return {}
return {
WORKSPACE_SLUG_HEADER: context.workspace_slug,
WORKSPACE_TYPE_HEADER: context.workspace_type,
}
def workspace_slug_for_canonical_permalinks() -> str | None:
"""Return the workspace slug when new permalinks should include it."""
context = current_workspace_permalink_context()
if context and context.should_prefix_permalinks:
return context.workspace_slug
return None
-27
View File
@@ -138,33 +138,6 @@ async def cleanup_global_db_after_test() -> AsyncGenerator[None, None]:
await db.shutdown_db()
@pytest.fixture(autouse=True)
def clean_routing_env(monkeypatch) -> None:
"""Keep CLI routing env mutations from leaking between integration tests."""
# Trigger: CLI integration tests exercise long-running MCP entrypoints that set routing env.
# Why: those commands normally own the process lifetime, but pytest keeps reusing it.
# Outcome: every integration test starts from neutral routing unless it opts in explicitly.
monkeypatch.delenv("BASIC_MEMORY_FORCE_LOCAL", raising=False)
monkeypatch.delenv("BASIC_MEMORY_FORCE_CLOUD", raising=False)
monkeypatch.delenv("BASIC_MEMORY_EXPLICIT_ROUTING", raising=False)
@pytest.fixture(autouse=True)
def isolate_data_dir_env(monkeypatch) -> None:
"""Keep host data-dir env vars from leaking into integration tests.
Why: GitHub Actions Ubuntu runners set ``XDG_CONFIG_HOME=/home/runner/.config``,
and ``resolve_data_dir()`` honors it ahead of ``Path.home() / ".basic-memory"``.
Without clearing it, the MCP tool process reads config.json from the host XDG
path instead of the tmp dir the ``config_manager`` fixture wrote to so
``test-project`` is missing from ``config.projects``, ``get_project_mode``
falls through to its CLOUD default (#837), and every tool call fails with
"Cloud routing requested but no credentials found."
"""
monkeypatch.delenv("BASIC_MEMORY_CONFIG_DIR", raising=False)
monkeypatch.delenv("XDG_CONFIG_HOME", raising=False)
POSTGRES_EPHEMERAL_TABLES = [
"search_vector_embeddings",
"search_vector_chunks",
@@ -1,81 +0,0 @@
"""Integration test for long prose before inline wikilinks.
Issue #721 was originally triggered by markdown bullets that contained inline
`[[wikilinks]]` preceded by long prose. The parser treated all prose before the
wikilink as `relation_type`, and the response model's former `MaxLen(200)`
constraint caused edit_note to fail with:
1 validation error for EntityResponseV2
relations.0.relation_type
String should have at most 200 characters
The relation grammar now fixes the root ambiguity too: unquoted multi-word
prefixes are prose, so this shape should index as a generic `links_to`
relation rather than preserving prose as a custom relation type.
"""
import pytest
from fastmcp import Client
from basic_memory.repository.relation_repository import RelationRepository
@pytest.mark.asyncio
async def test_edit_note_handles_long_prose_around_wikilink(
mcp_server, app, test_project, engine_factory
):
"""Long prose before an inline wikilink should not become a relation type."""
long_prose = (
"**Lorem ipsum dolor sit amet** — consectetur adipiscing elit, sed do eiusmod "
"tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, "
"quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo "
"consequat. Trust boundary model documented in"
)
assert len(long_prose) > 200, (
f"setup wrong: prose-before-link must exceed the historical 200-char cap, "
f"got {len(long_prose)} chars"
)
note_body = (
"# Long Relation Type Repro\n\n"
f"- {long_prose} [[Some Note Title]] for additional context.\n"
)
async with Client(mcp_server) as client:
# Create the note (file-write side; would already fail at index time
# if RelationType MaxLen were back).
write_result = await client.call_tool(
"write_note",
{
"project": test_project.name,
"title": "Long Relation Type Repro",
"directory": "issue721",
"content": note_body,
},
)
assert len(write_result.content) == 1
write_text = write_result.content[0].text
assert "Created note" in write_text or "Updated note" in write_text
# Edit the note. This triggers re-index → response model validation.
# With the historical MaxLen(200) cap, this would raise:
# "relations.0.relation_type String should have at most 200 characters"
edit_result = await client.call_tool(
"edit_note",
{
"project": test_project.name,
"identifier": "Long Relation Type Repro",
"operation": "append",
"content": "\n\nappended line\n",
},
)
assert len(edit_result.content) == 1
assert "Edited note (append)" in edit_result.content[0].text
_, session_maker = engine_factory
relation_repository = RelationRepository(session_maker, project_id=test_project.id)
links_to_relations = await relation_repository.find_by_type("links_to")
prose_type_relations = await relation_repository.find_by_type(long_prose)
assert any(relation.to_name == "Some Note Title" for relation in links_to_relations)
assert not prose_type_relations
@@ -1,565 +0,0 @@
"""
Integration tests for MCP tool parameter aliases.
Verifies that MCP tools accept training-data-friendly parameter aliases
(via Pydantic AliasChoices) alongside the canonical names, so models
that reach for `offset`/`limit`/`find`/`old_text` etc. don't hit
validation errors on first use.
See: https://github.com/basicmachines-co/basic-memory/issues/690
"""
import pytest
from fastmcp import Client
# --- read_note: pagination params removed in #693 (were no-ops) ---
# The `page` / `page_size` parameters were removed because the API endpoint
# silently dropped them. Search-fallback pagination is unrelated to read_note.
# --- edit_note: find_text / content / section aliases ---
@pytest.mark.asyncio
async def test_edit_note_accepts_find_alias_for_find_text(mcp_server, app, test_project):
"""`find` should map to `find_text` — the highest-frequency miss in the issue."""
async with Client(mcp_server) as client:
await client.call_tool(
"write_note",
{
"project": test_project.name,
"title": "Find Alias Note",
"directory": "test",
"content": "# Find Alias Note\n\nVersion v1.0.0 of the spec.",
},
)
result = await client.call_tool(
"edit_note",
{
"project": test_project.name,
"identifier": "Find Alias Note",
"operation": "find_replace",
"content": "v2.0.0",
"find": "v1.0.0", # alias for find_text
},
)
assert "Edited note (find_replace)" in result.content[0].text
read_result = await client.call_tool(
"read_note",
{"project": test_project.name, "identifier": "Find Alias Note"},
)
assert "v2.0.0" in read_result.content[0].text
assert "v1.0.0" not in read_result.content[0].text
@pytest.mark.asyncio
async def test_edit_note_accepts_old_text_alias(mcp_server, app, test_project):
"""`old_text` (diff/patch convention) should map to `find_text`."""
async with Client(mcp_server) as client:
await client.call_tool(
"write_note",
{
"project": test_project.name,
"title": "Old Text Note",
"directory": "test",
"content": "# Old Text Note\n\nThe quick brown fox.",
},
)
result = await client.call_tool(
"edit_note",
{
"project": test_project.name,
"identifier": "Old Text Note",
"operation": "find_replace",
"content": "lazy",
"old_text": "quick",
},
)
assert "Edited note (find_replace)" in result.content[0].text
@pytest.mark.asyncio
async def test_edit_note_accepts_new_content_alias_for_content(mcp_server, app, test_project):
"""`new_content` should map to `content` — `content` is ambiguous as 'replacement text'."""
async with Client(mcp_server) as client:
await client.call_tool(
"write_note",
{
"project": test_project.name,
"title": "New Content Note",
"directory": "test",
"content": "# New Content Note\n\nplaceholder",
},
)
result = await client.call_tool(
"edit_note",
{
"project": test_project.name,
"identifier": "New Content Note",
"operation": "find_replace",
"new_content": "actual value", # alias for content
"find_text": "placeholder",
},
)
assert "Edited note (find_replace)" in result.content[0].text
read_result = await client.call_tool(
"read_note",
{"project": test_project.name, "identifier": "New Content Note"},
)
assert "actual value" in read_result.content[0].text
@pytest.mark.asyncio
async def test_edit_note_accepts_section_heading_alias(mcp_server, app, test_project):
"""`section_heading` and `heading` should map to `section`."""
async with Client(mcp_server) as client:
await client.call_tool(
"write_note",
{
"project": test_project.name,
"title": "Section Heading Note",
"directory": "test",
"content": "# Section Heading Note\n\n## Notes\n\nold notes\n",
},
)
result = await client.call_tool(
"edit_note",
{
"project": test_project.name,
"identifier": "Section Heading Note",
"operation": "replace_section",
"content": "fresh notes\n",
"section_heading": "## Notes", # alias for section
},
)
assert "Edited note (replace_section)" in result.content[0].text
@pytest.mark.asyncio
async def test_edit_note_canonical_names_still_work(mcp_server, app, test_project):
"""Canonical names must keep working alongside aliases."""
async with Client(mcp_server) as client:
await client.call_tool(
"write_note",
{
"project": test_project.name,
"title": "Edit Canonical Note",
"directory": "test",
"content": "# Edit Canonical Note\n\nold-value here.",
},
)
result = await client.call_tool(
"edit_note",
{
"project": test_project.name,
"identifier": "Edit Canonical Note",
"operation": "find_replace",
"content": "new-value",
"find_text": "old-value",
},
)
assert "Edited note (find_replace)" in result.content[0].text
# --- search_notes aliases ---
@pytest.mark.asyncio
async def test_search_notes_accepts_query_aliases(mcp_server, app, test_project):
"""`q` (HTTP convention), `search`, and `text` should all map to `query`."""
async with Client(mcp_server) as client:
await client.call_tool(
"write_note",
{
"project": test_project.name,
"title": "Searchable Note",
"directory": "test",
"content": "# Searchable Note\n\nUnique-keyword-XYZ here.",
},
)
# Try each alias
for alias_key in ("q", "search", "text"):
result = await client.call_tool(
"search_notes",
{
"project": test_project.name,
alias_key: "Unique-keyword-XYZ",
"limit": 5, # also testing pagination alias
},
)
assert "Searchable Note" in result.content[0].text, f"alias {alias_key} failed"
@pytest.mark.asyncio
async def test_search_notes_accepts_after_date_aliases(mcp_server, app, test_project):
"""`since`/`after`/`from_date` should map to `after_date`."""
async with Client(mcp_server) as client:
await client.call_tool(
"write_note",
{
"project": test_project.name,
"title": "Date Filter Note",
"directory": "test",
"content": "# Date Filter Note\n\nbody",
},
)
# Just verify the alias is accepted at validation time (no error)
result = await client.call_tool(
"search_notes",
{"project": test_project.name, "query": "Date Filter", "since": "1d"},
)
assert result.content # didn't error
# --- recent_activity aliases ---
@pytest.mark.asyncio
async def test_recent_activity_accepts_timeframe_aliases(mcp_server, app, test_project):
"""`since`/`time_range`/`lookback` should map to `timeframe`."""
async with Client(mcp_server) as client:
result = await client.call_tool(
"recent_activity",
{"project": test_project.name, "since": "7d", "limit": 5},
)
assert result.content # accepted, no validation error
# --- list_directory aliases ---
@pytest.mark.asyncio
async def test_list_directory_accepts_directory_alias(mcp_server, app, test_project):
"""`directory`/`folder`/`path`/`dir` should all map to `dir_name`."""
async with Client(mcp_server) as client:
await client.call_tool(
"write_note",
{
"project": test_project.name,
"title": "Dir Test",
"directory": "list-dir-aliases",
"content": "# Dir Test\n\nbody",
},
)
for alias_key in ("directory", "folder", "path", "dir"):
result = await client.call_tool(
"list_directory",
{"project": test_project.name, alias_key: "/list-dir-aliases"},
)
assert "Dir Test" in result.content[0].text, f"alias {alias_key} failed"
@pytest.mark.asyncio
async def test_list_directory_accepts_glob_aliases(mcp_server, app, test_project):
"""`glob`/`pattern`/`filter` should map to `file_name_glob`."""
async with Client(mcp_server) as client:
await client.call_tool(
"write_note",
{
"project": test_project.name,
"title": "Glob Target",
"directory": "glob-test",
"content": "# Glob Target\n\nbody",
},
)
result = await client.call_tool(
"list_directory",
{
"project": test_project.name,
"dir_name": "/glob-test",
"glob": "*.md",
},
)
assert "Glob Target" in result.content[0].text
# --- write_note aliases ---
@pytest.mark.asyncio
async def test_write_note_accepts_directory_aliases(mcp_server, app, test_project):
"""`folder`/`dir`/`path` should map to `directory`."""
async with Client(mcp_server) as client:
result = await client.call_tool(
"write_note",
{
"project": test_project.name,
"title": "Folder Alias Note",
"folder": "folder-alias-test", # alias
"content": "# Folder Alias Note\n\nbody",
},
)
assert "folder-alias-test" in result.content[0].text
@pytest.mark.asyncio
async def test_write_note_overwrite_canonical_via_mcp(mcp_server, app, test_project):
"""Canonical overwrite=True must reach the handler (#818 regression)."""
async with Client(mcp_server) as client:
await client.call_tool(
"write_note",
{
"project": test_project.name,
"title": "Overwrite Canonical Note",
"directory": "overwrite-test",
"content": "v1",
},
)
blocked = await client.call_tool(
"write_note",
{
"project": test_project.name,
"title": "Overwrite Canonical Note",
"directory": "overwrite-test",
"content": "v2",
},
)
assert "# Error: Note already exists" in blocked.content[0].text
result = await client.call_tool(
"write_note",
{
"project": test_project.name,
"title": "Overwrite Canonical Note",
"directory": "overwrite-test",
"content": "v2",
"overwrite": True,
},
)
assert "# Updated note" in result.content[0].text
# --- move_note aliases ---
@pytest.mark.asyncio
async def test_move_note_accepts_destination_aliases(mcp_server, app, test_project):
"""`to`/`dest_path`/`new_path`/`destination` should map to `destination_path`."""
async with Client(mcp_server) as client:
await client.call_tool(
"write_note",
{
"project": test_project.name,
"title": "Move Target",
"directory": "move-src",
"content": "# Move Target\n\nbody",
},
)
result = await client.call_tool(
"move_note",
{
"project": test_project.name,
"identifier": "Move Target",
"to": "move-dest/Move Target.md", # alias for destination_path
},
)
assert "move-dest" in result.content[0].text
# --- read_content aliases ---
@pytest.mark.asyncio
async def test_read_content_accepts_file_path_alias(mcp_server, app, test_project):
"""`file_path`/`filepath`/`file` should map to `path`."""
async with Client(mcp_server) as client:
await client.call_tool(
"write_note",
{
"project": test_project.name,
"title": "Read Content Target",
"directory": "read-content-test",
"content": "# Read Content Target\n\nraw body",
},
)
result = await client.call_tool(
"read_content",
{
"project": test_project.name,
"file_path": "read-content-test/Read Content Target.md",
},
)
# read_content returns a dict; structured content should include the file
text = result.content[0].text if result.content else ""
struct = result.structured_content if hasattr(result, "structured_content") else None
assert "raw body" in text or (struct and "raw body" in str(struct))
# --- build_context aliases ---
@pytest.mark.asyncio
async def test_build_context_accepts_url_aliases(mcp_server, app, test_project):
"""`uri`/`memory_url` should map to `url`."""
async with Client(mcp_server) as client:
await client.call_tool(
"write_note",
{
"project": test_project.name,
"title": "Context Target",
"directory": "build-ctx",
"content": "# Context Target\n\nbody",
},
)
result = await client.call_tool(
"build_context",
{
"project": test_project.name,
"uri": "memory://build-ctx/context-target", # alias for url
},
)
# Just verify validation accepted the alias
assert result.content or result.structured_content
# --- view_note: pagination params removed in #693 (delegates to read_note) ---
# --- delete_note aliases ---
@pytest.mark.asyncio
async def test_delete_note_accepts_is_dir_alias(mcp_server, app, test_project):
"""`is_dir` should map to `is_directory` and route to single-note deletion."""
async with Client(mcp_server) as client:
await client.call_tool(
"write_note",
{
"project": test_project.name,
"title": "Delete Alias Note",
"directory": "delete-alias-test",
"content": "# Delete Alias Note\n\nBody.",
},
)
result = await client.call_tool(
"delete_note",
{
"project": test_project.name,
"identifier": "delete-alias-test/Delete Alias Note",
"is_dir": False, # alias for is_directory
},
)
# delete_note returns a bool/dict on success; just assert no error
assert result.content or result.structured_content
# --- Schema sanity check: aliases must not appear in the advertised schema ---
@pytest.mark.asyncio
async def test_aliases_not_advertised_in_schema(mcp_server, app):
"""The JSON schema sent to models should advertise only canonical names.
Aliases are accepted at validation time but advertising them would defeat
the purpose: we want the model to learn the canonical name, with aliases
as a silent safety net for first-use mistakes.
The `must_not_have` lists below intentionally include both *accepted*
aliases (which must stay hidden from the schema) AND *rejected* aliases
that were considered but deliberately omitted (`offset` for `page`,
`limit_related` for `max_related`). Listing rejected aliases here acts
as a future-contributor guard if anyone re-adds them, this test catches
it before the bad alias ships.
"""
async with Client(mcp_server) as client:
tools = {t.name: t for t in await client.list_tools()}
# tool_name -> (must_have_canonical, must_not_have_aliases)
checks = {
# read_note has no pagination params (#693 — they were no-ops; removed).
# The must_not_have list still includes the rejected aliases so future
# contributors don't reintroduce them.
"read_note": (
[],
["page", "page_size", "offset", "limit", "page_number", "per_page"],
),
"edit_note": (
["find_text", "section", "content"],
["find", "old_text", "old_content", "search", "new_content", "section_heading"],
),
"search_notes": (
["query", "page", "page_size", "note_types", "after_date", "min_similarity"],
[
"q",
"search",
"offset",
"limit",
"note_type",
"types",
"since",
"after",
"threshold",
],
),
"recent_activity": (
["type", "timeframe", "page", "page_size"],
["types", "kind", "since", "time_range", "lookback", "offset", "limit"],
),
"list_directory": (
["dir_name", "file_name_glob"],
["directory", "folder", "path", "dir", "glob", "pattern", "filter"],
),
"write_note": (
["directory", "overwrite"],
["folder", "dir", "path", "force", "replace"],
),
"move_note": (
["destination_path", "destination_folder", "is_directory"],
["dest_path", "new_path", "to", "destination", "is_dir"],
),
"delete_note": (["is_directory"], ["is_dir"]),
"read_content": (["path"], ["file_path", "filepath", "file"]),
# view_note pagination params removed in #693 (delegates to read_note).
"view_note": (
[],
["page", "page_size", "offset", "limit", "page_number", "per_page"],
),
"build_context": (
["url", "timeframe", "page", "page_size", "max_related"],
["uri", "memory_url", "since", "offset", "limit", "max_results", "limit_related"],
),
"canvas": (["directory"], ["folder", "dir", "path"]),
}
for tool_name, (must_have, must_not_have) in checks.items():
assert tool_name in tools, f"tool {tool_name} not registered"
props = tools[tool_name].inputSchema["properties"]
for canonical in must_have:
assert canonical in props, f"{tool_name}: canonical '{canonical}' missing"
for alias in must_not_have:
assert alias not in props, f"{tool_name}: alias '{alias}' leaked into schema"
# #818: AliasChoices on optional bool broke external-client JSON schema (null-only).
overwrite_schema = tools["write_note"].inputSchema["properties"]["overwrite"]
schema_types: set[str] = set()
if "type" in overwrite_schema:
raw = overwrite_schema["type"]
if isinstance(raw, str):
schema_types.add(raw)
else:
schema_types.update(raw)
for option in overwrite_schema.get("anyOf", ()):
if "type" in option:
schema_types.add(option["type"])
assert "boolean" in schema_types, (
f"write_note overwrite must expose boolean in schema, got {overwrite_schema}"
)
@@ -588,122 +588,3 @@ async def test_nested_project_paths_rejected(mcp_server, app, test_project, tmp_
# Clean up parent project
await client.call_tool("delete_project", {"project_name": parent_name})
@pytest.mark.asyncio
async def test_create_project_accepts_workspace_in_local_mode(
mcp_server, app, test_project, tmp_path
):
"""Passing workspace via the MCP wire is accepted by the tool schema and
does not break the local create path.
In local mode there is no cloud factory installed, so workspace is a no-op:
the request lands on the ASGI transport which has no workspace concept. This
test guards the schema so a future change can't accidentally drop the parameter.
"""
async with Client(mcp_server) as client:
create_result = await client.call_tool(
"create_memory_project",
{
"project_name": "ws-local-test",
"project_path": str(
tmp_path.parent / (tmp_path.name + "-projects") / "project-ws-local-test"
),
"workspace": "team-paul",
},
)
assert len(create_result.content) == 1
create_text = create_result.content[0].text # pyright: ignore [reportAttributeAccessIssue]
assert "" in create_text
assert "ws-local-test" in create_text
list_result = await client.call_tool("list_memory_projects", {})
assert "ws-local-test" in list_result.content[0].text # pyright: ignore [reportAttributeAccessIssue]
@pytest.mark.asyncio
async def test_create_project_workspace_slug_forwarded_to_factory_as_tenant_id(
mcp_server, app, test_project, tmp_path
):
"""workspace slug resolves before the tenant id flows to the cloud factory.
Simulates the cloud MCP server pattern (set_client_factory) and verifies the
factory receives the workspace argument. This is the chicken-and-egg case:
no project_id exists yet, so workspace is the only way to target a
non-default workspace at create time.
"""
from contextlib import asynccontextmanager
from unittest.mock import AsyncMock, patch
from httpx import ASGITransport, AsyncClient as HttpxAsyncClient
from basic_memory.mcp import async_client
from basic_memory.mcp.tools import project_management
from basic_memory.schemas.cloud import WorkspaceInfo
captured_workspaces: list[str | None] = []
resolved_workspace = WorkspaceInfo(
tenant_id="tenant-cloud-test",
name="Team Paul",
workspace_type="organization",
slug="team-paul",
role="owner",
organization_id="org-team-paul",
is_default=False,
has_active_subscription=True,
)
@asynccontextmanager
async def fake_factory(workspace=None):
captured_workspaces.append(workspace)
# Yield an ASGI-backed httpx client so the create_project HTTP call
# actually reaches the FastAPI app and the project is created in the DB.
async with HttpxAsyncClient(
transport=ASGITransport(app=app), base_url="http://test"
) as inner:
yield inner
original_factory = async_client._client_factory
async_client.set_client_factory(fake_factory)
try:
with patch.object(
project_management,
"resolve_workspace_parameter",
new_callable=AsyncMock,
return_value=resolved_workspace,
) as mock_resolve_workspace:
async with Client(mcp_server) as mcp_client:
create_result = await mcp_client.call_tool(
"create_memory_project",
{
"project_name": "ws-routed-project",
"project_path": str(
tmp_path.parent
/ (tmp_path.name + "-projects")
/ "project-ws-routed-project"
),
"workspace": "team-paul",
},
)
create_text = create_result.content[0].text # pyright: ignore [reportAttributeAccessIssue]
assert "" in create_text
assert "ws-routed-project" in create_text
mock_resolve_workspace.assert_awaited_once()
await_args = mock_resolve_workspace.await_args
assert await_args is not None
assert await_args.kwargs["workspace"] == "team-paul"
# The factory must have been invoked with the tenant id resolved from the slug.
# create_memory_project opens one get_client() context, so the factory is
# called once per tool invocation; both list_projects and create_project
# share that single client.
assert captured_workspaces, "Factory was never invoked"
assert all(ws == "tenant-cloud-test" for ws in captured_workspaces), (
"Expected workspace='tenant-cloud-test' on every factory call, "
f"got {captured_workspaces}"
)
finally:
async_client._client_factory = original_factory
@@ -100,71 +100,3 @@ async def test_read_note_underscored_folder_by_permalink(mcp_server, app, test_p
assert "# Example Note" in result_text
assert "This is a test note in an underscored folder." in result_text
assert f"{test_project.name}/archive/articles/example-note" in result_text # permalink
@pytest.mark.asyncio
async def test_read_note_by_project_id(mcp_server, app, test_project):
"""Read a note by passing project_id (UUID) instead of project name.
Verifies the project_id parameter routes through get_project_client correctly
in pure local mode (no cloud creds), where get_project_mode() would otherwise
default unknown identifiers to CLOUD and break routing.
"""
async with Client(mcp_server) as client:
await client.call_tool(
"write_note",
{
"project": test_project.name,
"title": "By ID Note",
"directory": "test",
"content": "# By ID Note\n\nLooked up by external_id.",
},
)
# Read by external_id (UUID) instead of project name
read_result = await client.call_tool(
"read_note",
{
"project_id": test_project.external_id,
"identifier": "By ID Note",
},
)
assert len(read_result.content) == 1
assert read_result.content[0].type == "text"
result_text = read_result.content[0].text
assert "# By ID Note" in result_text
assert "Looked up by external_id." in result_text
@pytest.mark.asyncio
async def test_read_note_project_id_takes_precedence_over_name(mcp_server, app, test_project):
"""When project_id is passed alongside a wrong project name, project_id wins."""
async with Client(mcp_server) as client:
await client.call_tool(
"write_note",
{
"project": test_project.name,
"title": "Precedence Note",
"directory": "test",
"content": "# Precedence Note\n\nproject_id wins.",
},
)
# Pass an obviously-wrong project name alongside the correct project_id.
# If project_id takes precedence (as documented), the read still succeeds.
read_result = await client.call_tool(
"read_note",
{
"project": "this-project-does-not-exist",
"project_id": test_project.external_id,
"identifier": "Precedence Note",
},
)
assert len(read_result.content) == 1
result_text = read_result.content[0].text
assert "# Precedence Note" in result_text
assert "project_id wins." in result_text
@@ -28,7 +28,6 @@ async def test_search_notes_entity_types_as_string(mcp_server, app, test_project
{
"project": test_project.name,
"query": "coercion",
"search_type": "text",
"entity_types": '["entity"]',
},
)
@@ -55,7 +54,6 @@ async def test_search_notes_note_types_as_string(mcp_server, app, test_project):
{
"project": test_project.name,
"query": "coercion",
"search_type": "text",
"note_types": '["note"]',
},
)
@@ -83,7 +81,6 @@ async def test_search_notes_tags_as_string(mcp_server, app, test_project):
{
"project": test_project.name,
"query": "tagged",
"search_type": "text",
"tags": '["alpha"]',
},
)
@@ -110,7 +107,6 @@ async def test_search_notes_metadata_filters_as_string(mcp_server, app, test_pro
{
"project": test_project.name,
"query": "metadata",
"search_type": "text",
"metadata_filters": '{"type": "note"}',
},
)
@@ -1,509 +0,0 @@
"""Integration coverage for local, cloud, and team permalink routing."""
from __future__ import annotations
import json
from collections.abc import Iterable
from contextlib import asynccontextmanager, contextmanager
from pathlib import Path
from typing import Any
import pytest
import pytest_asyncio
from fastmcp import Client
from httpx import ASGITransport, AsyncClient as HttpxAsyncClient
from basic_memory.config import BasicMemoryConfig, ConfigManager, ProjectEntry
from basic_memory.mcp import async_client
from basic_memory.mcp import project_context
from basic_memory.models import Project
from basic_memory.repository.project_repository import ProjectRepository
from basic_memory.schemas.cloud import WorkspaceInfo
from basic_memory.workspace_context import workspace_permalink_headers
def _json_content(tool_result) -> Any:
"""Parse a FastMCP tool result content block into JSON."""
assert len(tool_result.content) == 1
assert tool_result.content[0].type == "text"
return json.loads(tool_result.content[0].text) # pyright: ignore [reportAttributeAccessIssue]
def _workspace(
*,
tenant_id: str,
slug: str,
workspace_type: str,
is_default: bool = True,
) -> WorkspaceInfo:
return WorkspaceInfo(
tenant_id=tenant_id,
name=slug.replace("-", " ").title(),
workspace_type=workspace_type,
slug=slug,
role="owner",
organization_id=None,
is_default=is_default,
has_active_subscription=True,
)
@pytest.fixture
def personal_workspace() -> WorkspaceInfo:
return _workspace(
tenant_id="personal-tenant",
slug="personal",
workspace_type="personal",
)
@pytest.fixture
def team_workspace() -> WorkspaceInfo:
return _workspace(
tenant_id="team-tenant",
slug="team-paul",
workspace_type="organization",
is_default=False,
)
@pytest.fixture
def route_workspaces(app):
@contextmanager
def route(*workspaces: WorkspaceInfo, forward_permalink_headers: bool = True):
with _workspace_routing(
app,
workspaces,
forward_permalink_headers=forward_permalink_headers,
):
yield
return route
@pytest_asyncio.fixture
async def alternate_project(
config_home,
engine_factory,
app_config: BasicMemoryConfig,
config_manager: ConfigManager,
) -> Project:
"""Create a second project so no-project lookups cannot pass via the default."""
alternate_path = Path(config_home) / "alternate-project"
alternate_path.mkdir(parents=True, exist_ok=True)
_, session_maker = engine_factory
project_repository = ProjectRepository(session_maker)
project = await project_repository.create(
{
"name": "alternate-project",
"description": "Non-default project for prefix routing tests",
"path": str(alternate_path),
"is_active": True,
"is_default": False,
}
)
app_config.projects[project.name] = ProjectEntry(path=str(alternate_path))
config_manager.save_config(app_config)
return project
def _save_permalink_config(
app_config: BasicMemoryConfig,
*,
include_project: bool,
default_project: str | None,
) -> None:
app_config.permalinks_include_project = include_project
app_config.default_project = default_project
ConfigManager().save_config(app_config)
@contextmanager
def _workspace_routing(
app,
workspaces: Iterable[WorkspaceInfo],
*,
forward_permalink_headers: bool = True,
):
"""Route MCP tool HTTP calls through an ASGI-backed cloud workspace seam."""
workspace_list = tuple(workspaces)
workspace_ids = {workspace.tenant_id for workspace in workspace_list}
async def workspace_provider():
return list(workspace_list)
@asynccontextmanager
async def factory(workspace: str | None = None):
assert workspace is None or workspace in workspace_ids
headers = workspace_permalink_headers() if forward_permalink_headers else {}
async with HttpxAsyncClient(
transport=ASGITransport(app=app),
base_url="http://test",
headers=headers,
) as inner:
yield inner
original_factory = async_client._client_factory
original_workspace_provider = project_context._workspace_provider
async_client.set_client_factory(factory)
project_context.set_workspace_provider(workspace_provider)
try:
yield
finally:
async_client._client_factory = original_factory
project_context._workspace_provider = original_workspace_provider
async def _call_json(mcp_server, tool_name: str, arguments: dict[str, Any]) -> dict[str, Any]:
async with Client(mcp_server) as client:
result = await client.call_tool(tool_name, arguments)
payload = _json_content(result)
assert isinstance(payload, dict)
return payload
async def _write_json(
mcp_server,
*,
project: str,
title: str,
directory: str = "permalink-suite",
) -> dict[str, Any]:
return await _call_json(
mcp_server,
"write_note",
{
"project": project,
"title": title,
"directory": directory,
"content": f"# {title}\n\nUnique body for {title}.",
"output_format": "json",
},
)
async def _read_json(
mcp_server,
*,
identifier: str,
project: str | None = None,
) -> dict[str, Any]:
arguments = {
"identifier": identifier,
"output_format": "json",
}
if project is not None:
arguments["project"] = project
return await _call_json(mcp_server, "read_note", arguments)
async def _search_single_permalink(
mcp_server,
*,
title: str,
project: str | None = None,
) -> str:
arguments = {
"query": title,
"search_type": "text",
"output_format": "json",
}
if project is not None:
arguments["project"] = project
payload = await _call_json(mcp_server, "search_notes", arguments)
matching_results = [
item for item in payload["results"] if isinstance(item, dict) and item.get("title") == title
]
assert len(matching_results) == 1
permalink = matching_results[0].get("permalink")
assert isinstance(permalink, str)
return permalink
async def _search_permalink_exact(
mcp_server,
*,
permalink: str,
title: str,
project: str | None = None,
) -> str:
arguments = {
"query": permalink,
"search_type": "permalink",
"output_format": "json",
}
if project is not None:
arguments["project"] = project
payload = await _call_json(mcp_server, "search_notes", arguments)
matching_results = [
item for item in payload["results"] if isinstance(item, dict) and item.get("title") == title
]
assert len(matching_results) == 1
result_permalink = matching_results[0].get("permalink")
assert isinstance(result_permalink, str)
return result_permalink
@pytest.mark.asyncio
async def test_local_short_permalink_round_trips_when_project_is_supplied(
mcp_server,
test_project,
app_config,
):
"""Local short IDs need the project argument for write/search/read routing."""
_save_permalink_config(app_config, include_project=False, default_project=None)
title = "Local Short Permalink"
expected_permalink = "permalink-suite/local-short-permalink"
write_payload = await _write_json(mcp_server, project=test_project.name, title=title)
assert write_payload["permalink"] == expected_permalink
assert (
await _search_single_permalink(mcp_server, project=test_project.name, title=title)
== expected_permalink
)
short_read = await _read_json(
mcp_server,
project=test_project.name,
identifier=expected_permalink,
)
assert short_read["permalink"] == expected_permalink
@pytest.mark.asyncio
async def test_local_project_permalink_routes_without_project_argument(
mcp_server,
alternate_project,
app_config,
):
"""Local project-qualified IDs carry enough route context for search/read."""
_save_permalink_config(app_config, include_project=True, default_project=None)
title = "Local Project Permalink"
short_permalink = "permalink-suite/local-project-permalink"
expected_permalink = f"{alternate_project.name}/{short_permalink}"
write_payload = await _write_json(mcp_server, project=alternate_project.name, title=title)
assert write_payload["permalink"] == expected_permalink
assert (
await _search_permalink_exact(
mcp_server,
permalink=expected_permalink,
title=title,
)
== expected_permalink
)
project_read = await _read_json(mcp_server, identifier=expected_permalink)
assert project_read["permalink"] == expected_permalink
@pytest.mark.asyncio
async def test_personal_cloud_short_permalink_round_trips_when_project_is_supplied(
mcp_server,
test_project,
app_config,
personal_workspace,
route_workspaces,
):
"""Legacy short IDs remain readable/searchable in a personal cloud workspace."""
_save_permalink_config(app_config, include_project=False, default_project=None)
title = "Personal Cloud Short Permalink"
expected_permalink = "permalink-suite/personal-cloud-short-permalink"
write_payload = await _write_json(mcp_server, project=test_project.name, title=title)
assert write_payload["permalink"] == expected_permalink
with route_workspaces(personal_workspace):
assert (
await _search_single_permalink(
mcp_server,
project=test_project.name,
title=title,
)
== expected_permalink
)
short_read = await _read_json(
mcp_server,
project=test_project.name,
identifier=expected_permalink,
)
assert short_read["permalink"] == expected_permalink
@pytest.mark.asyncio
async def test_personal_cloud_project_permalink_routes_without_project_argument(
mcp_server,
alternate_project,
app_config,
personal_workspace,
route_workspaces,
):
"""Legacy project-qualified cloud IDs carry enough route context."""
_save_permalink_config(app_config, include_project=True, default_project=None)
title = "Personal Cloud Project Permalink"
short_permalink = "permalink-suite/personal-cloud-project-permalink"
expected_permalink = f"{alternate_project.name}/{short_permalink}"
write_payload = await _write_json(mcp_server, project=alternate_project.name, title=title)
assert write_payload["permalink"] == expected_permalink
with route_workspaces(personal_workspace):
assert (
await _search_permalink_exact(
mcp_server,
permalink=expected_permalink,
title=title,
)
== expected_permalink
)
project_read = await _read_json(mcp_server, identifier=expected_permalink)
assert project_read["permalink"] == expected_permalink
@pytest.mark.asyncio
async def test_team_short_permalink_round_trips_when_project_is_supplied(
mcp_server,
test_project,
app_config,
team_workspace,
route_workspaces,
):
"""Team short IDs need the qualified project argument for search/read routing."""
team_project = f"{team_workspace.slug}/{test_project.name}"
_save_permalink_config(app_config, include_project=False, default_project=None)
title = "Team Short Permalink"
expected_permalink = "permalink-suite/team-short-permalink"
write_payload = await _write_json(mcp_server, project=test_project.name, title=title)
assert write_payload["permalink"] == expected_permalink
with route_workspaces(team_workspace):
assert (
await _search_single_permalink(
mcp_server,
project=team_project,
title=title,
)
== expected_permalink
)
short_read = await _read_json(
mcp_server,
project=team_project,
identifier=expected_permalink,
)
assert short_read["permalink"] == expected_permalink
@pytest.mark.asyncio
async def test_team_project_permalink_routes_without_project_argument(
mcp_server,
alternate_project,
app_config,
team_workspace,
route_workspaces,
):
"""Team project-qualified IDs carry enough route context for search/read."""
_save_permalink_config(app_config, include_project=True, default_project=None)
title = "Team Project Permalink"
short_permalink = "permalink-suite/team-project-permalink"
expected_permalink = f"{alternate_project.name}/{short_permalink}"
write_payload = await _write_json(mcp_server, project=alternate_project.name, title=title)
assert write_payload["permalink"] == expected_permalink
with route_workspaces(team_workspace):
assert (
await _search_permalink_exact(
mcp_server,
permalink=expected_permalink,
title=title,
)
== expected_permalink
)
project_read = await _read_json(mcp_server, identifier=expected_permalink)
assert project_read["permalink"] == expected_permalink
@pytest.mark.asyncio
async def test_team_workspace_permalink_routes_to_specific_workspace(
mcp_server,
test_project,
app_config,
personal_workspace,
team_workspace,
route_workspaces,
):
"""Workspace-qualified IDs route to the project in that workspace."""
_save_permalink_config(app_config, include_project=True, default_project=None)
team_project = f"{team_workspace.slug}/{test_project.name}"
title = "Team Workspace Permalink"
short_permalink = "permalink-suite/team-workspace-permalink"
expected_permalink = f"{team_workspace.slug}/{test_project.name}/{short_permalink}"
with route_workspaces(personal_workspace, team_workspace):
write_payload = await _write_json(mcp_server, project=team_project, title=title)
assert write_payload["permalink"] == expected_permalink
assert (
await _search_permalink_exact(
mcp_server,
permalink=expected_permalink,
title=title,
)
== expected_permalink
)
workspace_read = await _read_json(mcp_server, identifier=expected_permalink)
assert workspace_read["permalink"] == expected_permalink
@pytest.mark.asyncio
async def test_write_note_by_project_id_qualifies_permalink_when_headers_not_forwarded(
mcp_server,
test_project,
app_config,
team_workspace,
route_workspaces,
):
"""MCP writes should return self-routing IDs even if the API omits slug headers."""
_save_permalink_config(app_config, include_project=True, default_project=None)
title = "Project Id Workspace Permalink"
short_permalink = "permalink-suite/project-id-workspace-permalink"
expected_permalink = f"{team_workspace.slug}/{test_project.name}/{short_permalink}"
with route_workspaces(team_workspace, forward_permalink_headers=False):
write_payload = await _call_json(
mcp_server,
"write_note",
{
"project_id": test_project.external_id,
"title": title,
"directory": "permalink-suite",
"content": f"# {title}\n\nProject ID workspace body.",
"output_format": "json",
},
)
assert write_payload["permalink"] == expected_permalink
workspace_read = await _read_json(
mcp_server,
identifier=f"memory://{write_payload['permalink']}",
)
assert workspace_read["title"] == title
+6 -12
View File
@@ -10,8 +10,6 @@ pytest
# Run tests against Postgres only (requires docker-compose)
docker-compose -f docker-compose-postgres.yml up -d
BASIC_MEMORY_TEST_POSTGRES=1 \
POSTGRES_TEST_URL=postgresql+asyncpg://basic_memory_user:dev_password@localhost:5433/basic_memory \
pytest -m postgres
# Run tests against BOTH backends
@@ -56,7 +54,7 @@ database_url = None # Uses default SQLite path
# Postgres config
database_backend = DatabaseBackend.POSTGRES
database_url = "postgresql+asyncpg://basic_memory_user:dev_password@localhost:5433/basic_memory"
database_url = "postgresql+asyncpg://basic_memory_user:dev_password@localhost:5433/basic_memory_test"
```
## Running Postgres Tests
@@ -68,22 +66,18 @@ docker-compose -f docker-compose-postgres.yml up -d
```
This starts:
- Postgres 17 with **pgvector** (`pgvector/pgvector:pg17`) on port **5433** (not 5432 to avoid conflicts)
- Database: `basic_memory`
- Postgres 17 on port **5433** (not 5432 to avoid conflicts)
- Test database: `basic_memory_test`
- Credentials: `basic_memory_user` / `dev_password`
### 2. Run Postgres Tests
```bash
# Run only Postgres tests
BASIC_MEMORY_TEST_POSTGRES=1 \
POSTGRES_TEST_URL=postgresql+asyncpg://basic_memory_user:dev_password@localhost:5433/basic_memory \
pytest -m postgres
# Run specific test with Postgres
BASIC_MEMORY_TEST_POSTGRES=1 \
POSTGRES_TEST_URL=postgresql+asyncpg://basic_memory_user:dev_password@localhost:5433/basic_memory \
pytest tests/repository/test_entity_repository.py::test_create -m postgres
pytest tests/test_entity_repository.py::test_create -m postgres
# Skip Postgres tests (default behavior)
pytest -m "not postgres"
@@ -127,7 +121,7 @@ jobs:
# Postgres service container
services:
postgres:
image: pgvector/pgvector:pg17
image: postgres:17
env:
POSTGRES_DB: basic_memory_test
POSTGRES_USER: basic_memory_user
@@ -175,4 +169,4 @@ docker-compose -f docker-compose-postgres.yml exec postgres pg_isready -U basic_
- [ ] Add `--run-all-backends` CLI flag to run both backends in sequence
- [ ] Implement test fixtures for backend-specific features (e.g., Postgres full-text search vs SQLite FTS5)
- [ ] Add performance comparison benchmarks between backends
- [ ] Add performance comparison benchmarks between backends
-17
View File
@@ -482,23 +482,6 @@ async def test_import_missing_file(client: AsyncClient, v2_project_url: str):
assert response.status_code in [400, 422] # Either bad request or unprocessable entity
@pytest.mark.asyncio
async def test_import_rejects_oversized_file(
client: AsyncClient, tmp_path, app_config, v2_project_url: str
):
"""Import endpoints should reject files before parsing unbounded JSON."""
app_config.import_upload_max_bytes = 8
file_path = tmp_path / "large.json"
file_path.write_text(json.dumps([{"message": "too large"}]), encoding="utf-8")
with open(file_path, "rb") as f:
files = {"file": ("large.json", f, "application/json")}
response = await client.post(f"{v2_project_url}/import/chatgpt", files=files)
assert response.status_code == 413
assert "maximum size" in response.json()["detail"]
@pytest.mark.asyncio
async def test_import_empty_file(client: AsyncClient, tmp_path, v2_project_url: str):
"""Test importing an empty file via v2 endpoint."""
+1 -1
View File
@@ -302,7 +302,7 @@ async def test_create_entity_with_observations_and_relations(
## Observations
- [note] This is a test observation #tag1 (context)
- "related to" [[OtherEntity]]
- related to [[OtherEntity]]
""",
}
-79
View File
@@ -55,25 +55,6 @@ class SpyEntityRepository:
self.calls.append(ids)
return [self.entities_by_id[i] for i in ids if i in self.entities_by_id]
async def find_by_ids_for_hydration(self, ids: list[int]):
self.calls.append(ids)
return [self.entities_by_id[i] for i in ids if i in self.entities_by_id]
class LightweightOnlyEntityRepository:
"""Raises if graph hydration uses the eager-loading repository method."""
def __init__(self, entities_by_id: dict[int, SimpleNamespace]):
self.entities_by_id = entities_by_id
self.hydration_calls: list[list[int]] = []
async def find_by_ids(self, ids: list[int]):
raise AssertionError("graph hydration must use the lightweight hydration lookup")
async def find_by_ids_for_hydration(self, ids: list[int]):
self.hydration_calls.append(ids)
return [self.entities_by_id[i] for i in ids if i in self.entities_by_id]
# --- Single batch fetch (N+1 elimination) ---
@@ -217,63 +198,3 @@ async def test_to_graph_context_empty_results_skip_entity_lookup():
assert repo.calls == []
assert list(graph.results) == []
@pytest.mark.asyncio
async def test_to_graph_context_uses_lightweight_hydration_lookup():
"""Hydration should not load observations/relations when only entity fields are needed."""
repo = LightweightOnlyEntityRepository(
{
1: _make_entity(1, "Root", "ext-root"),
2: _make_entity(2, "Child", "ext-child"),
}
)
now = datetime.now(timezone.utc)
context = ServiceContextResult(
results=[
ContextResultItem(
primary_result=_make_row(
type="entity",
id=1,
root_id=1,
title="Root",
permalink="notes/root",
file_path="notes/root.md",
created_at=now,
),
observations=[],
related_results=[
_make_row(
type="relation",
id=20,
root_id=1,
title="links_to: Child",
permalink="notes/root",
file_path="notes/root.md",
relation_type="links_to",
from_id=1,
to_id=2,
depth=1,
created_at=now,
)
],
)
],
metadata=ContextMetadata(
types=[SearchItemType.ENTITY, SearchItemType.RELATION],
depth=1,
primary_count=1,
related_count=1,
total_relations=1,
),
)
graph = await to_graph_context(context, entity_repository=repo)
assert len(repo.hydration_calls) == 1
assert set(repo.hydration_calls[0]) == {1, 2}
relation = graph.results[0].related_results[0]
assert isinstance(relation, RelationSummary)
assert relation.from_entity_external_id == "ext-root"
assert relation.to_entity_external_id == "ext-child"
+52 -36
View File
@@ -8,48 +8,50 @@ from httpx import AsyncClient
async def test_get_orphan_entities_empty_project(client: AsyncClient, v2_project_url):
"""An empty project returns an empty orphans list."""
response = await client.get(f"{v2_project_url}/knowledge/orphans")
assert response.status_code == 200
assert response.json() == {"entities": [], "total": 0}
data = response.json()
assert data["entities"] == []
assert data["total"] == 0
@pytest.mark.asyncio
async def test_get_orphan_entities_returns_unlinked_entities(client: AsyncClient, v2_project_url):
async def test_get_orphan_entities_returns_unlinked_entities(
client: AsyncClient, v2_project_url
):
"""Entities with no relations appear in the orphans endpoint."""
first = await client.post(
r1 = await client.post(
f"{v2_project_url}/knowledge/entities",
json={"title": "Orphan One", "directory": "orphan", "content": "No links here"},
)
second = await client.post(
assert r1.status_code == 200
r2 = await client.post(
f"{v2_project_url}/knowledge/entities",
json={"title": "Orphan Two", "directory": "orphan", "content": "Also no links"},
)
assert first.status_code == 200
assert second.status_code == 200
assert r2.status_code == 200
response = await client.get(f"{v2_project_url}/knowledge/orphans")
assert response.status_code == 200
data = response.json()
titles = {entity["title"] for entity in data["entities"]}
assert titles == {"Orphan One", "Orphan Two"}
assert "entities" in data
assert "total" in data
titles = {e["title"] for e in data["entities"]}
assert "Orphan One" in titles
assert "Orphan Two" in titles
assert data["total"] == len(data["entities"])
assert data["total"] == 2
@pytest.mark.asyncio
async def test_get_orphan_entities_excludes_incoming_and_outgoing_relation_nodes(
async def test_get_orphan_entities_excludes_entity_with_outgoing_relation(
client: AsyncClient, v2_project_url
):
"""Entities with either side of a resolved relation are excluded from orphans."""
target = await client.post(
f"{v2_project_url}/knowledge/entities",
json={
"title": "Target Note",
"directory": "linked",
"content": "Referenced entity",
},
)
source = await client.post(
"""An entity with an outgoing wiki-link relation is excluded from orphans."""
# Source entity references another via wikilink in content
r_source = await client.post(
f"{v2_project_url}/knowledge/entities",
json={
"title": "Source Note",
@@ -57,36 +59,50 @@ async def test_get_orphan_entities_excludes_incoming_and_outgoing_relation_nodes
"content": "- links_to [[Target Note]]",
},
)
standalone = await client.post(
assert r_source.status_code == 200
# Target entity (no outgoing links)
await client.post(
f"{v2_project_url}/knowledge/entities",
json={"title": "Standalone Note", "directory": "linked", "content": "No links"},
json={"title": "Target Note", "directory": "linked", "content": "Referenced entity"},
)
# Unlinked entity - should appear in orphans
await client.post(
f"{v2_project_url}/knowledge/entities",
json={"title": "Standalone Note", "directory": "linked", "content": "No links at all"},
)
assert source.status_code == 200
assert target.status_code == 200
assert standalone.status_code == 200
response = await client.get(f"{v2_project_url}/knowledge/orphans")
assert response.status_code == 200
titles = {entity["title"] for entity in response.json()["entities"]}
data = response.json()
titles = {e["title"] for e in data["entities"]}
# Source has outgoing relation — not an orphan
assert "Source Note" not in titles
assert "Target Note" not in titles
# Standalone has no links — is an orphan
assert "Standalone Note" in titles
@pytest.mark.asyncio
async def test_get_orphan_entities_response_shape(client: AsyncClient, v2_project_url):
"""Each orphan entity in the response has the expected graph-node fields."""
created = await client.post(
"""Each entity in the response has the expected fields."""
await client.post(
f"{v2_project_url}/knowledge/entities",
json={"title": "Shape Test", "directory": "shape", "content": "Testing shape"},
json={"title": "Shape Test", "directory": "shape", "content": "Testing response shape"},
)
assert created.status_code == 200
response = await client.get(f"{v2_project_url}/knowledge/orphans")
assert response.status_code == 200
data = response.json()
entity = next(entity for entity in data["entities"] if entity["title"] == "Shape Test")
assert set(entity) == {"external_id", "title", "note_type", "file_path"}
assert data["total"] >= 1
entity = next(e for e in data["entities"] if e["title"] == "Shape Test")
assert "external_id" in entity
assert "title" in entity
assert "file_path" in entity
assert "note_type" in entity
assert entity["title"] == "Shape Test"
assert entity["file_path"].endswith(".md")
-15
View File
@@ -321,21 +321,6 @@ async def test_resolve_project_by_permalink(
assert resolved.resolution_method in ["name", "permalink"]
@pytest.mark.asyncio
async def test_resolve_project_by_workspace_qualified_permalink(
client: AsyncClient, test_project: Project, v2_projects_url
):
"""Resolve the workspace/project form shown by MCP disambiguation errors."""
resolve_data = {"identifier": f"personal/{test_project.name}"}
response = await client.post(f"{v2_projects_url}/resolve", json=resolve_data)
assert response.status_code == 200
resolved = ProjectResolveResponse.model_validate(response.json())
assert resolved.external_id == test_project.external_id
assert resolved.name == test_project.name
assert resolved.resolution_method == "permalink"
@pytest.mark.asyncio
async def test_resolve_project_by_id(client: AsyncClient, test_project: Project, v2_projects_url):
"""Test resolving a project by external_id string returns correct project external_id."""
+10 -156
View File
@@ -57,7 +57,7 @@ async def test_search_entities(
)
# Search for the entity
response = await client.post(f"{v2_project_url}/search/", json={"text": "Searchable"})
response = await client.post(f"{v2_project_url}/search/", json={"search_text": "Searchable"})
assert response.status_code == 200
data = response.json()
@@ -94,7 +94,7 @@ async def test_search_with_pagination(
# Search with pagination
response = await client.post(
f"{v2_project_url}/search/",
json={"text": "Search Entity"},
json={"search_text": "Search Entity"},
params={"page": 1, "page_size": 3},
)
@@ -102,57 +102,6 @@ async def test_search_with_pagination(
data = response.json()
assert data["current_page"] == 1
assert data["page_size"] == 3
assert data["total"] == 5
assert data["has_more"] is True
response = await client.post(
f"{v2_project_url}/search/",
json={"text": "Search Entity"},
params={"page": 2, "page_size": 3},
)
assert response.status_code == 200
data = response.json()
assert data["current_page"] == 2
assert data["page_size"] == 3
assert data["total"] == 5
assert data["has_more"] is False
assert len(data["results"]) == 2
@pytest.mark.asyncio
async def test_search_with_item_type_filter_returns_total(
client: AsyncClient,
test_project: Project,
v2_project_url: str,
entity_repository,
search_service,
file_service,
):
"""Metadata-only graph searches should include exact totals for pagination."""
for i in range(5):
entity_data = {
"title": f"Structured Entity {i}",
"note_type": "note",
"content_type": "text/markdown",
"file_path": f"structured_{i}.md",
"checksum": f"structuredsum{i}",
}
await create_test_entity(
test_project, entity_data, entity_repository, search_service, file_service
)
response = await client.post(
f"{v2_project_url}/search/",
json={"entity_types": ["entity"]},
params={"page": 1, "page_size": 3},
)
assert response.status_code == 200
data = response.json()
assert data["total"] == 5
assert data["has_more"] is True
assert len(data["results"]) == 3
@pytest.mark.asyncio
@@ -243,7 +192,7 @@ async def test_search_with_type_filter(
# Search with type filter
response = await client.post(
f"{v2_project_url}/search/", json={"text": "Type", "note_types": ["note"]}
f"{v2_project_url}/search/", json={"search_text": "Type", "note_types": ["note"]}
)
assert response.status_code == 200
@@ -276,7 +225,7 @@ async def test_search_with_date_filter(
# Search with date filter
response = await client.post(
f"{v2_project_url}/search/",
json={"text": "Date Filtered", "after_date": "2024-01-01T00:00:00Z"},
json={"search_text": "Date Filtered", "after_date": "2024-01-01T00:00:00Z"},
)
assert response.status_code == 200
@@ -297,42 +246,12 @@ async def test_search_empty_query(
assert response.status_code in [200, 422]
@pytest.mark.asyncio
async def test_search_whitespace_text_is_treated_as_empty(
client: AsyncClient,
test_project: Project,
v2_project_url: str,
entity_repository,
search_service,
file_service,
):
"""Whitespace-only text should not become an unfiltered project-wide search."""
entity_data = {
"title": "Whitespace Regression Entity",
"note_type": "note",
"content_type": "text/markdown",
"file_path": "whitespace_regression.md",
"checksum": "whitespace123",
}
await create_test_entity(
test_project, entity_data, entity_repository, search_service, file_service
)
response = await client.post(f"{v2_project_url}/search/", json={"text": " "})
assert response.status_code == 200
data = response.json()
assert data["total"] == 0
assert data["has_more"] is False
assert data["results"] == []
@pytest.mark.asyncio
async def test_search_invalid_project_id(
client: AsyncClient,
):
"""Test searching with invalid project ID returns 404."""
response = await client.post("/v2/projects/999999/search/", json={"text": "test"})
response = await client.post("/v2/projects/999999/search/", json={"search_text": "test"})
assert response.status_code == 404
@@ -372,7 +291,7 @@ async def test_v2_search_endpoints_use_project_id_not_name(
):
"""Test that v2 search endpoints reject string project names."""
# Try to use project name instead of ID - should fail
response = await client.post(f"/v2/{test_project.name}/search/", json={"text": "test"})
response = await client.post(f"/v2/{test_project.name}/search/", json={"search_text": "test"})
# FastAPI path validation should reject non-integer project_id
assert response.status_code in [404, 422]
@@ -388,14 +307,11 @@ async def test_search_router_returns_400_for_semantic_disabled(
async def search(self, *args, **kwargs):
raise SemanticSearchDisabledError("Semantic search is disabled for this project.")
async def count(self, *args, **kwargs):
raise SemanticSearchDisabledError("Semantic search is disabled for this project.")
app.dependency_overrides[get_search_service_v2_external] = lambda: RaisingSearchService()
try:
response = await client.post(
f"{v2_project_url}/search/",
json={"text": "semantic query", "retrieval_mode": "vector"},
json={"search_text": "semantic query", "retrieval_mode": "vector"},
)
finally:
app.dependency_overrides.pop(get_search_service_v2_external, None)
@@ -414,14 +330,11 @@ async def test_search_router_returns_400_for_semantic_missing_deps(
async def search(self, *args, **kwargs):
raise SemanticDependenciesMissingError("Semantic dependencies are missing.")
async def count(self, *args, **kwargs):
raise SemanticDependenciesMissingError("Semantic dependencies are missing.")
app.dependency_overrides[get_search_service_v2_external] = lambda: RaisingSearchService()
try:
response = await client.post(
f"{v2_project_url}/search/",
json={"text": "semantic query", "retrieval_mode": "hybrid"},
json={"search_text": "semantic query", "retrieval_mode": "hybrid"},
)
finally:
app.dependency_overrides.pop(get_search_service_v2_external, None)
@@ -440,9 +353,6 @@ async def test_search_router_returns_400_for_invalid_vector_query(
async def search(self, *args, **kwargs):
raise ValueError("Vector retrieval requires a text query.")
async def count(self, *args, **kwargs):
raise ValueError("Vector retrieval requires a text query.")
app.dependency_overrides[get_search_service_v2_external] = lambda: RaisingSearchService()
try:
response = await client.post(
@@ -456,56 +366,6 @@ async def test_search_router_returns_400_for_invalid_vector_query(
assert "Vector retrieval requires a text query" in response.json()["detail"]
@pytest.mark.asyncio
async def test_semantic_search_uses_probe_pagination_without_count(
client: AsyncClient,
app,
v2_project_url: str,
):
"""Semantic searches should not run an extra count query."""
now = datetime.now(timezone.utc)
fake_rows = [
SearchIndexRow(
project_id=1,
id=row_id,
type="entity",
file_path=f"notes/semantic-{row_id}.md",
created_at=now,
updated_at=now,
title=f"Semantic Result {row_id}",
permalink=f"notes/semantic-{row_id}",
score=1.0 - (row_id / 10),
)
for row_id in range(1, 4)
]
class FakeSearchService:
async def search(self, query, *, limit, offset):
assert query.retrieval_mode.value == "vector"
assert limit == 3
assert offset == 0
return fake_rows
async def count(self, *args, **kwargs):
raise AssertionError("semantic search must not run count")
app.dependency_overrides[get_search_service_v2_external] = lambda: FakeSearchService()
try:
response = await client.post(
f"{v2_project_url}/search/",
json={"text": "semantic query", "retrieval_mode": "vector"},
params={"page": 1, "page_size": 2},
)
finally:
app.dependency_overrides.pop(get_search_service_v2_external, None)
assert response.status_code == 200
data = response.json()
assert data["total"] == 0
assert data["has_more"] is True
assert len(data["results"]) == 2
@pytest.mark.asyncio
async def test_search_has_more_when_more_results_exist(
client: AsyncClient,
@@ -599,14 +459,11 @@ async def test_search_result_includes_matched_chunk(
async def search(self, *args, **kwargs):
return [fake_row]
async def count(self, *args, **kwargs):
return 1
app.dependency_overrides[get_search_service_v2_external] = lambda: FakeSearchService()
try:
response = await client.post(
f"{v2_project_url}/search/",
json={"text": "pricing"},
json={"search_text": "pricing"},
)
finally:
app.dependency_overrides.pop(get_search_service_v2_external, None)
@@ -643,14 +500,11 @@ async def test_search_result_omits_matched_chunk_when_none(
async def search(self, *args, **kwargs):
return [fake_row]
async def count(self, *args, **kwargs):
return 1
app.dependency_overrides[get_search_service_v2_external] = lambda: FakeSearchService()
try:
response = await client.post(
f"{v2_project_url}/search/",
json={"text": "general"},
json={"search_text": "general"},
)
finally:
app.dependency_overrides.pop(get_search_service_v2_external, None)
@@ -23,9 +23,6 @@ async def test_search_router_wraps_request_in_manual_operation(monkeypatch) -> N
async def search(self, query, *, limit, offset):
return []
async def count(self, query):
return 0
@contextmanager
def fake_span(name: str, **attrs):
operations.append((name, attrs))
@@ -1,41 +0,0 @@
"""Tests for workspace permalink context headers."""
import pytest
from httpx import AsyncClient
from basic_memory.workspace_context import WORKSPACE_SLUG_HEADER, WORKSPACE_TYPE_HEADER
@pytest.mark.asyncio
@pytest.mark.parametrize(
"headers, expected_detail",
[
(
{WORKSPACE_SLUG_HEADER: "team-paul"},
"workspace_slug and workspace_type must be provided together",
),
(
{
WORKSPACE_SLUG_HEADER: "../team-paul",
WORKSPACE_TYPE_HEADER: "organization",
},
f"{WORKSPACE_SLUG_HEADER} must match [a-z0-9_-]+",
),
(
{
WORKSPACE_SLUG_HEADER: "team-paul",
WORKSPACE_TYPE_HEADER: "enterprise",
},
f"{WORKSPACE_TYPE_HEADER} must be one of: organization, personal",
),
],
)
async def test_workspace_permalink_headers_fail_fast(
client: AsyncClient,
headers: dict[str, str],
expected_detail: str,
):
response = await client.get("/v2/projects/", headers=headers)
assert response.status_code == 400
assert response.json()["detail"] == expected_detail
@@ -12,21 +12,6 @@ from basic_memory.config import ProjectMode
runner = CliRunner()
@pytest.mark.parametrize(
"command",
["sync", "bisync", "check", "bisync-reset", "sync-setup"],
)
def test_cloud_sync_command_help_marks_personal_workspace_only(command):
"""Cloud sync help should explain that local mirrors are Personal-only."""
importlib.import_module("basic_memory.cli.commands.cloud.project_sync")
result = runner.invoke(app, ["cloud", command, "--help"])
assert result.exit_code == 0, result.output
assert "Personal workspace local mirror only" in result.output
assert "Not supported for Team workspaces" in result.output
@pytest.mark.parametrize(
"argv",
[

Some files were not shown because too many files have changed in this diff Show More