From ef32ca23089e352516a764ba51a3fd7776062faa Mon Sep 17 00:00:00 2001 From: phernandez Date: Wed, 28 Oct 2026 16:14:40 -0500 Subject: [PATCH 1/3] fix(mcp): require explicit project scope for note tools Require nonempty project scope on note, folder, context and schema tools. Preserve explicit multi-project search, resolve saved prompt defaults before dispatch, and update manual and recovery guidance. Refs #1919. Signed-off-by: phernandez --- docs/1.0.md | 17 +- src/basic_memory/man/man3/bm-context(3).md | 6 +- src/basic_memory/man/man3/bm-delete(3).md | 8 +- src/basic_memory/man/man3/bm-edit(3).md | 10 +- src/basic_memory/man/man3/bm-find(3).md | 12 +- src/basic_memory/man/man3/bm-list(3).md | 24 ++- src/basic_memory/man/man3/bm-move(3).md | 6 +- src/basic_memory/man/man3/bm-project(3).md | 7 +- src/basic_memory/man/man3/bm-read(3).md | 14 +- src/basic_memory/man/man3/bm-schema(3).md | 6 +- src/basic_memory/man/man3/bm-search(3).md | 11 +- src/basic_memory/man/man3/bm-write(3).md | 10 +- src/basic_memory/mcp/directory_listing.py | 6 +- src/basic_memory/mcp/note_targets.py | 11 +- .../mcp/prompts/continue_conversation.py | 15 +- .../mcp/prompts/recent_activity.py | 41 ++-- src/basic_memory/mcp/refusals.py | 17 +- .../mcp/resources/ai_assistant_guide.md | 7 +- src/basic_memory/mcp/server.py | 8 +- src/basic_memory/mcp/tool_params.py | 25 ++- src/basic_memory/mcp/tools/chatgpt_tools.py | 4 +- src/basic_memory/mcp/tools/context.py | 3 +- src/basic_memory/mcp/tools/delete.py | 13 +- src/basic_memory/mcp/tools/edit.py | 9 +- src/basic_memory/mcp/tools/find_files.py | 3 +- src/basic_memory/mcp/tools/listing.py | 47 +---- src/basic_memory/mcp/tools/move.py | 15 +- src/basic_memory/mcp/tools/note_schemas.py | 3 +- src/basic_memory/mcp/tools/projects.py | 14 +- src/basic_memory/mcp/tools/ranked_search.py | 16 +- src/basic_memory/mcp/tools/read.py | 5 +- src/basic_memory/mcp/tools/view_note.py | 12 +- src/basic_memory/mcp/tools/write.py | 35 ++-- tests/mcp/test_first_connect_onboarding.py | 2 +- tests/mcp/test_note_targets.py | 8 +- tests/mcp/test_prompts.py | 2 +- .../mcp/test_recent_activity_prompt_modes.py | 32 ++-- tests/mcp/test_required_project.py | 178 ++++++++++++++++++ tests/mcp/test_resources.py | 2 +- tests/mcp/test_tool_bm_context.py | 6 +- tests/mcp/test_tool_bm_delete.py | 4 +- tests/mcp/test_tool_bm_edit.py | 3 +- tests/mcp/test_tool_bm_list.py | 32 ++-- tests/mcp/test_tool_bm_move.py | 26 ++- tests/mcp/test_tool_bm_project.py | 33 +--- tests/mcp/test_tool_bm_read.py | 4 +- tests/mcp/test_tool_bm_search.py | 13 +- tests/mcp/test_tool_bm_write.py | 35 +++- tests/mcp/test_tool_params.py | 7 +- 49 files changed, 552 insertions(+), 275 deletions(-) create mode 100644 tests/mcp/test_required_project.py diff --git a/docs/1.0.md b/docs/1.0.md index 19b1dd404..f87e8748d 100644 --- a/docs/1.0.md +++ b/docs/1.0.md @@ -188,7 +188,7 @@ The primary surface has twelve tools, plus the separately enabled destructive | `bm_move` | Move a note or directory to `destination`. A trailing slash means move into that directory under the source's existing name; without it, the destination is the new path. | | `bm_search` | Ranked text, title, permalink, semantic, or hybrid search; metadata filters; project scopes; and matching-line searches. Replaces both note search and the MCP grep workflow. | | `bm_context` | Build graph context from an exact `identifier`, with bounded depth and time window. Whitespace-only identifiers are refused. | -| `bm_list` | List one directory level. Root discovery exposes addressable project mounts; use returned scope for follow-up calls. | +| `bm_list` | List one directory level in the required project. `/` is that project's root; discover projects with `bm_project(command="list")`. | | `bm_find` | Recursive file discovery with path and frontmatter filters. Use this for inventory rather than expecting recursive `bm_list` results. | | `bm_project` | Consolidate `list`, `create`, and `recent`. Project rows carry workspace metadata; deletion is not a command on this tool. | | `bm_project_delete` | Separate, opt-in destructive project deletion. Keep it separate in tool permissions and agent allowlists. | @@ -197,7 +197,7 @@ The primary surface has twelve tools, plus the separately enabled destructive ### Change arguments and response handling too -- Pass names, workspace-qualified names, or external UUIDs through `project`. +- Pass names, workspace-qualified names, or external UUIDs through required `project`. Remove `project_id`; calls do not retain a selected project between requests. - Search uses `mode`, `filters`, `items`, `since`, and `all_projects` instead of `search_type`, `metadata_filters`, `entity_types`, `after_date`, and @@ -251,11 +251,16 @@ surface they were measured against and should not be relabeled as 1.0 results. ### Project routing and refusal handling -- With multiple addressable projects, core note/search calls require an explicit - `project` or a recognized project-qualified target, even if a default project - is configured. A single-project constraint can supply the scope implicitly. +- Core note, folder, context and schema calls require a nonempty `project`, + including single-project sessions, constrained servers and qualified targets. + Discovery (`bm_project(command="list")`) and bundled manuals need no project. + `bm_project(command="recent")` requires `project` too. +- Search requires explicit scope: `project` for one project, `projects` for + selected projects, or `all_projects=True` for all accessible projects. A + project-qualified path or memory URL does not replace explicit search scope. - A relative path such as `notes/topic.md` does not select a project merely - because it contains a slash. Use returned qualified identifiers or pass scope. + because it contains a slash. Pass scope with every call; qualified identifiers + must agree with that scope. Restart MCP clients to refresh required parameters. - Search resolves project-qualified `memory://` URLs without rewriting stored project-qualified permalinks into workspace-qualified identities. - Native ChatGPT search/fetch and saved search/continue prompts resolve their diff --git a/src/basic_memory/man/man3/bm-context(3).md b/src/basic_memory/man/man3/bm-context(3).md index a70aef923..c6df20cb6 100644 --- a/src/basic_memory/man/man3/bm-context(3).md +++ b/src/basic_memory/man/man3/bm-context(3).md @@ -18,8 +18,8 @@ verified: 0.24.1 mcp ## SYNOPSIS ``` -bm_context(identifier, depth=1, since="7d", max_related=10, compact=False, - page=1, page_size=10, output_format="json", project=None) +bm_context(identifier, project, depth=1, since="7d", max_related=10, + compact=False, page=1, page_size=10, output_format="json") ``` ## DESCRIPTION @@ -41,6 +41,7 @@ one. ## PARAMETERS - **identifier** (string, required) — Where to start: a note path, permalink, memory:// URL, or a pattern such as 'specs/*'. +- **project** (string, required) — Required project name, 'workspace/project', or project external id. Discover projects with bm_project(command='list'). Paths are relative to this project; a qualified path must agree with it. - **depth** (integer, optional, default: 1) — Relation hops to follow (1-5). - **since** (string, optional, default: "7d") — How far back to look: '7d', '24h', '2 days ago', 'last week', or a date. Windows shorter than one day are widened to one day. - **max_related** (integer, optional, default: 10) — Most related results to return (0-100). @@ -48,7 +49,6 @@ one. - **page** (integer, optional, default: 1) — Page number. - **page_size** (integer, optional, default: 10) — Primary results per page (1-50). - **output_format** (optional, default: "json") -- **project** (string | null, optional, default: None) — Project name, 'workspace/project', or project external id. With multiple addressable projects, scope note and search calls explicitly with this parameter or a project-qualified target. ## EXAMPLES diff --git a/src/basic_memory/man/man3/bm-delete(3).md b/src/basic_memory/man/man3/bm-delete(3).md index dd00a7f9e..3b640be4f 100644 --- a/src/basic_memory/man/man3/bm-delete(3).md +++ b/src/basic_memory/man/man3/bm-delete(3).md @@ -18,8 +18,8 @@ verified: 0.24.1 mcp ## SYNOPSIS ``` -bm_delete(identifier=None, path=None, recursive=False, - expected_checksum=None, output_format="text", project=None) +bm_delete(project, identifier=None, path=None, recursive=False, + expected_checksum=None, output_format="text") ``` ## DESCRIPTION @@ -34,12 +34,12 @@ be undone. ## PARAMETERS +- **project** (string, required) — Required project name, 'workspace/project', or project external id. Discover projects with bm_project(command='list'). Paths are relative to this project; a qualified path must agree with it. - **identifier** (string | null, optional, default: None) — The note to delete: a path, permalink, memory:// URL or exact title. - **path** (string | null, optional, default: None) — The directory to delete, with everything in it. - **recursive** (boolean, optional, default: False) — Required true to delete a directory and everything under it. - **expected_checksum** (string | null, optional, default: None) — Delete the note only while it is still this revision (from bm_read). - **output_format** (optional, default: "text") -- **project** (string | null, optional, default: None) — Project name, 'workspace/project', or project external id. With multiple addressable projects, scope note and search calls explicitly with this parameter or a project-qualified target. ## EXAMPLES @@ -47,7 +47,7 @@ be undone. bm_delete(path="old", project="demo") # → error: INVALID_ARGUMENTS: 'old' is a directory with 1 entries at its top level. # Deleting it removes everything under it. -# Try instead: bm_delete(path='old', recursive=true) +# Try instead: bm_delete(path='old', recursive=true, project='') bm_delete(path="old", recursive=True, project="demo") # → Deleted directory old (1 files) diff --git a/src/basic_memory/man/man3/bm-edit(3).md b/src/basic_memory/man/man3/bm-edit(3).md index 0d16f6122..dc70543c0 100644 --- a/src/basic_memory/man/man3/bm-edit(3).md +++ b/src/basic_memory/man/man3/bm-edit(3).md @@ -18,9 +18,9 @@ verified: 0.24.1 mcp ## SYNOPSIS ``` -bm_edit(identifier, command, content=None, section=None, find_text=None, - expected_replacements=1, replace_subsections=True, metadata=None, - expected_checksum=None, output_format="text", project=None) +bm_edit(identifier, command, project, content=None, section=None, + find_text=None, expected_replacements=1, replace_subsections=True, + metadata=None, expected_checksum=None, output_format="text") ``` ## DESCRIPTION @@ -44,6 +44,7 @@ missing note is an error; create notes with bm_write. - **identifier** (string, required) — The note or file: a file path ('notes/plan.md'), permalink, memory:// URL, exact title, external id, or '/path'. - **command** (required) — The edit. +- **project** (string, required) — Required project name, 'workspace/project', or project external id. Discover projects with bm_project(command='list'). Paths are relative to this project; a qualified path must agree with it. - **content** (string | null, optional, default: None) — The text to add or the replacement. Not used by set_metadata. - **section** (string | null, optional, default: None) — The heading for section commands: "Decisions", "Auth/Decisions" for one under "Auth", or "Decisions[1]" for the second of two. - **find_text** (string | null, optional, default: None) — For find_replace: the exact, case-sensitive text to replace. @@ -52,7 +53,6 @@ missing note is an error; create notes with bm_write. - **metadata** (object | null, optional, default: None) — Frontmatter fields to set; other fields are kept. - **expected_checksum** (string | null, optional, default: None) — Edit only while the note is still this revision (from bm_read). - **output_format** (optional, default: "text") -- **project** (string | null, optional, default: None) — Project name, 'workspace/project', or project external id. With multiple addressable projects, scope note and search calls explicitly with this parameter or a project-qualified target. ## EXAMPLES @@ -73,7 +73,7 @@ bm_edit(identifier="plans/launch-plan.md", command="append", content="x", expected_checksum="stale", project="demo") # → error: REVISION_CONFLICT: 'plans/launch-plan.md' changed since you read it # (current checksum 77a457af…). Nothing was changed. -# Try instead: bm_read(identifier='plans/launch-plan.md'), then retry with +# Try instead: bm_read(identifier='plans/launch-plan.md', project='demo'), then retry with # expected_checksum='77a457af…' ``` diff --git a/src/basic_memory/man/man3/bm-find(3).md b/src/basic_memory/man/man3/bm-find(3).md index 7cabab965..a2ce00f67 100644 --- a/src/basic_memory/man/man3/bm-find(3).md +++ b/src/basic_memory/man/man3/bm-find(3).md @@ -18,8 +18,8 @@ verified: 0.24.1 mcp ## SYNOPSIS ``` -bm_find(path="/", name=None, filters=None, fields=None, depth=10, page=1, - page_size=10, output_format="text", project=None) +bm_find(project, path="/", name=None, filters=None, fields=None, depth=10, + page=1, page_size=10, output_format="text") ``` ## DESCRIPTION @@ -28,7 +28,7 @@ Searches a folder and everything under it. With `name`, matches file names against a glob (`*meeting*`). With `filters`, matches notes by frontmatter, e.g. `{"status": "active"}` or `{"priority": {"$in": ["high"]}}`; `fields` returns just those frontmatter values per note. `path` limits the search to a -folder, and `/` searches another project. +folder within the required `project`. A qualified path must agree with it. For ranked text or meaning search, use bm_search. @@ -36,6 +36,7 @@ The shell counterpart is find(1). ## PARAMETERS +- **project** (string, required) — Required project name, 'workspace/project', or project external id. Discover projects with bm_project(command='list'). Paths are relative to this project; a qualified path must agree with it. - **path** (string, optional, default: "/") — A directory in the project, e.g. 'specs' or 'specs/active'. '/' is the project root; '/path' addresses another project. - **name** (string | null, optional, default: None) — File-name glob, e.g. '*.md'. Not with `filters`. - **filters** (object | null, optional, default: None) — Frontmatter filters as {field: condition}. Nested fields use dot notation ("schema.confidence"). A condition is a value for equality ({"status": "draft"}), null for absent-or-null ({"owner": null}), a list for contains-all ({"tags": ["a", "b"]}), or an operator object with $gt, $gte, $lt, $lte, $in, $between, $contains or $exists, e.g. {"priority": {"$in": ["high"]}}. Several operators on one field AND together. @@ -44,17 +45,16 @@ The shell counterpart is find(1). - **page** (integer, optional, default: 1) — Page number. - **page_size** (integer, optional, default: 10) — Results per page (1-100). - **output_format** (optional, default: "text") -- **project** (string | null, optional, default: None) — Project name, 'workspace/project', or project external id. With multiple addressable projects, scope note and search calls explicitly with this parameter or a project-qualified target. ## EXAMPLES ``` -bm_find(path="demo/", name="*plan*") +bm_find(path="demo/", name="*plan*", project="demo") # → Files under 'demo/' matching '*plan*': # 📁 plans /demo/plans # 📄 launch-plan.md demo/plans/launch-plan.md | launch-plan | … -bm_find(path="demo/", filters={"status": "active"}, fields=["status"]) +bm_find(path="demo/", filters={"status": "active"}, fields=["status"], project="demo") # → 1 notes under 'demo/' match: # - demo/plans/launch-plan.md | launch-plan | status='active' ``` diff --git a/src/basic_memory/man/man3/bm-list(3).md b/src/basic_memory/man/man3/bm-list(3).md index c34471229..e30d92091 100644 --- a/src/basic_memory/man/man3/bm-list(3).md +++ b/src/basic_memory/man/man3/bm-list(3).md @@ -18,16 +18,16 @@ verified: 0.24.1 mcp ## SYNOPSIS ``` -bm_list(path="/", glob=None, sort=None, page=1, page_size=10, - output_format="text", project=None) +bm_list(project, path="/", glob=None, sort=None, page=1, page_size=10, + output_format="text") ``` ## DESCRIPTION Lists one level of a folder: subfolders first, then files with their title, -date and id. `bm_list(path="/")` with no project lists the projects you can -address; `/path` lists inside another project, and the paths that come -back carry the same prefix. +date and id. `project` is required, including when `path="/"` lists its root. +Discover available projects with `bm_project(command="list")`. A qualified path +must agree with `project`; returned paths keep that prefix. Filter files with `glob` and order them with `sort`. Results are paged; the text output ends with the call for the next page. For a recursive search by name or @@ -37,36 +37,34 @@ The shell counterpart is ls(1). ## PARAMETERS +- **project** (string, required) — Required project name, 'workspace/project', or project external id. Discover projects with bm_project(command='list'). Paths are relative to this project; a qualified path must agree with it. - **path** (string, optional, default: "/") — A directory in the project, e.g. 'specs' or 'specs/active'. '/' is the project root; '/path' addresses another project. - **glob** (string | null, optional, default: None) — File-name glob, e.g. '*.md' or '*meeting*'. - **sort** (string | null, optional, default: None) — File order. Folders always come first. - **page** (integer, optional, default: 1) — Page number. - **page_size** (integer, optional, default: 10) — Results per page (1-100). - **output_format** (optional, default: "text") -- **project** (string | null, optional, default: None) — Project name, 'workspace/project', or project external id. With multiple addressable projects, scope note and search calls explicitly with this parameter or a project-qualified target. ## EXAMPLES ``` -bm_list(path="/") -# → Projects: -# 📁 demo /demo -# 📁 main /main +bm_list(path="/", project="demo") +# → Contents of '/': +# 📁 plans /plans bm_list(path="plans", project="demo") # → Contents of 'plans': # 📄 launch-plan.md plans/launch-plan.md | launch-plan | 2026-10-23 | id: 686e696d… # 📄 Release Checklist.md plans/Release Checklist.md | Release Checklist | 2026-10-23 | id: 7bf40fbe… -bm_list(path="demo/plans", sort="title_asc", output_format="json") +bm_list(path="demo/plans", sort="title_asc", output_format="json", project="demo") # → {"nodes": [{"name": "launch-plan.md", "file_path": "demo/plans/launch-plan.md", # "type": "file", "title": "launch-plan", ...}, ...], "page": 1, "has_more": false} ``` ## GOTCHAS -- `glob` and `sort` apply to files in a folder; on the project listing at `/` - they are refused. +- `glob` and `sort` apply to files in a folder, including the project root `/`. ## SEE ALSO diff --git a/src/basic_memory/man/man3/bm-move(3).md b/src/basic_memory/man/man3/bm-move(3).md index e27d0fba7..5287bda3a 100644 --- a/src/basic_memory/man/man3/bm-move(3).md +++ b/src/basic_memory/man/man3/bm-move(3).md @@ -18,8 +18,8 @@ verified: 0.24.1 mcp ## SYNOPSIS ``` -bm_move(destination, identifier=None, path=None, expected_checksum=None, - output_format="text", project=None) +bm_move(destination, project, identifier=None, path=None, + expected_checksum=None, output_format="text") ``` ## DESCRIPTION @@ -40,11 +40,11 @@ bm_write it there, then bm_delete the original. ## PARAMETERS - **destination** (string, required) — New path, e.g. 'archive/plan.md'. A trailing '/' ('archive/') moves the note or directory into that folder under its current name. +- **project** (string, required) — Required project name, 'workspace/project', or project external id. Discover projects with bm_project(command='list'). Paths are relative to this project; a qualified path must agree with it. - **identifier** (string | null, optional, default: None) — The note to move: a path, permalink, memory:// URL or exact title. - **path** (string | null, optional, default: None) — The directory to move, with everything in it, e.g. 'drafts/2025'. - **expected_checksum** (string | null, optional, default: None) — Move the note only while it is still this revision (from bm_read). - **output_format** (optional, default: "text") -- **project** (string | null, optional, default: None) — Project name, 'workspace/project', or project external id. With multiple addressable projects, scope note and search calls explicitly with this parameter or a project-qualified target. ## EXAMPLES diff --git a/src/basic_memory/man/man3/bm-project(3).md b/src/basic_memory/man/man3/bm-project(3).md index 5f9c32723..7dd97ac81 100644 --- a/src/basic_memory/man/man3/bm-project(3).md +++ b/src/basic_memory/man/man3/bm-project(3).md @@ -30,8 +30,7 @@ bm_project(command, name=None, path=None, set_default=False, workspace=None, - `list` — the projects you can address, grouped by workspace. - `create` — add a project: `name`, `path`, optional `set_default` and `workspace`. -- `recent` — what changed lately: `since`, `items`, paging. `project` picks the - project, else the default project; with no default, every project. JSON +- `recent` — what changed lately in the required `project`: `since`, `items`, paging. JSON output carries `page`, `page_size` and `has_more`, plus `guidance` for any project that was never indexed. @@ -56,7 +55,7 @@ The shell counterpart for `recent` is tail(1). - **page** (integer, optional, default: 1) — Page number. - **page_size** (integer, optional, default: 10) — Results per page (1-100). - **output_format** (optional, default: "text") -- **project** (string | null, optional, default: None) — Project name, 'workspace/project', or project external id. With multiple addressable projects, scope note and search calls explicitly with this parameter or a project-qualified target. +- **project** (string | null, optional, default: None) — Project name, 'workspace/project', or external id. Required for one-project operations; search may instead use `projects` or `all_projects=true`. Project discovery needs no scope. ## EXAMPLES @@ -71,7 +70,7 @@ bm_project(command="list") # - demo (local) [b2a21302…] # - main (local) [9b4d5944…] -bm_project(command="recent", since="1d") +bm_project(command="recent", since="1d", project="demo") # → ## Recent Activity: demo (1d) # **📄 Recent Notes & Documents (1):** # • launch-plan (plans) [id: 686e696d…] diff --git a/src/basic_memory/man/man3/bm-read(3).md b/src/basic_memory/man/man3/bm-read(3).md index 15bd9a238..dc87ef377 100644 --- a/src/basic_memory/man/man3/bm-read(3).md +++ b/src/basic_memory/man/man3/bm-read(3).md @@ -18,9 +18,9 @@ verified: 0.24.1 mcp ## SYNOPSIS ``` -bm_read(identifier, section=None, start_line=None, end_line=None, +bm_read(identifier, project, section=None, start_line=None, end_line=None, max_tokens=None, include_frontmatter=True, include_content=True, - output_format="text", project=None) + output_format="text") ``` Cloud additionally supports the following hosted signature. These options are not @@ -56,6 +56,7 @@ The shell counterpart is cat(1). ## PARAMETERS - **identifier** (string, required) — The note or file: a file path ('notes/plan.md'), permalink, memory:// URL, exact title, external id, or '/path'. +- **project** (string, required) — Required project name, 'workspace/project', or project external id. Discover projects with bm_project(command='list'). Paths are relative to this project; a qualified path must agree with it. - **section** (string | null, optional, default: None) — A heading to read: "Decisions", "Auth/Decisions" for a heading under "Auth", or "Decisions[1]" for the second "Decisions" heading. - **start_line** (integer | null, optional, default: None) - **end_line** (integer | null, optional, default: None) @@ -63,7 +64,6 @@ The shell counterpart is cat(1). - **include_frontmatter** (boolean, optional, default: True) — Include the YAML frontmatter in a whole-note read. - **include_content** (boolean, optional, default: True) — False returns only title, paths, checksum and updated_at. - **output_format** (optional, default: "text") -- **project** (string | null, optional, default: None) — Project name, 'workspace/project', or project external id. With multiple addressable projects, scope note and search calls explicitly with this parameter or a project-qualified target. ## CLOUD PARAMETERS @@ -106,7 +106,7 @@ bm_read(identifier="plans/launch-plan.md", include_content=False, # "file_path": "plans/launch-plan.md", "checksum": "13e0d14c…", # "updated_at": "2026-10-23T14:47:04.550062-05:00"} -bm_read(identifier="demo/plans/launch-plan.md", start_line=1, end_line=4) +bm_read(identifier="demo/plans/launch-plan.md", start_line=1, end_line=4, project="demo") # → Lines 1-4 of 21 (document, including frontmatter); next: start_line=5, end_line=8 # 1: --- # 2: title: launch-plan @@ -114,13 +114,13 @@ bm_read(identifier="demo/plans/launch-plan.md", start_line=1, end_line=4) bm_read(identifier="plans/missing.md", project="demo") # → error: NOT_FOUND: No note matches 'plans/missing.md' in project 'demo'. -# Try instead: bm_search(query='plans/missing.md') +# Try instead: bm_search(query='plans/missing.md', project='') ``` ## GOTCHAS -- With more than one project, an unqualified identifier is refused even when a - default project is set. Pass `project`, or qualify the path (`demo/plans/...`). +- `project` is required even with one configured project, a server project + constraint, or a qualified identifier. A qualified path must agree with it. - A section read returns numbered lines, like `start_line`/`end_line`; a whole note comes back without line numbers. - The token budget is approximate. The first nonblank line is returned whole diff --git a/src/basic_memory/man/man3/bm-schema(3).md b/src/basic_memory/man/man3/bm-schema(3).md index f26e97c1e..71d2688ee 100644 --- a/src/basic_memory/man/man3/bm-schema(3).md +++ b/src/basic_memory/man/man3/bm-schema(3).md @@ -18,8 +18,8 @@ verified: 0.24.1 mcp ## SYNOPSIS ``` -bm_schema(command, note_type=None, identifier=None, threshold=0.25, - output_format="text", project=None) +bm_schema(command, project, note_type=None, identifier=None, threshold=0.25, + output_format="text") ``` ## DESCRIPTION @@ -40,11 +40,11 @@ create one. ## PARAMETERS - **command** (required) — What to do. +- **project** (string, required) — Required project name, 'workspace/project', or project external id. Discover projects with bm_project(command='list'). Paths are relative to this project; a qualified path must agree with it. - **note_type** (string | null, optional, default: None) — The frontmatter `type:` to check. Required for infer and diff. - **identifier** (string | null, optional, default: None) — For validate: one note, instead of a whole note type. - **threshold** (number, optional, default: 0.25) — For infer: the share of notes a field must appear in to be suggested. - **output_format** (optional, default: "text") -- **project** (string | null, optional, default: None) — Project name, 'workspace/project', or project external id. With multiple addressable projects, scope note and search calls explicitly with this parameter or a project-qualified target. ## EXAMPLES diff --git a/src/basic_memory/man/man3/bm-search(3).md b/src/basic_memory/man/man3/bm-search(3).md index 5efec279e..1f090d3bd 100644 --- a/src/basic_memory/man/man3/bm-search(3).md +++ b/src/basic_memory/man/man3/bm-search(3).md @@ -45,6 +45,12 @@ are paged; read full notes with bm_read. The shell counterpart is grep(1). +Every search needs explicit project scope: `project` for one project, `projects` +for a list, or `all_projects=True` for all accessible projects. A path or +`memory://` query does not replace that requirement. For a one-project search, +`identifier`, `path` or a `memory://` query narrows within the selected project. +Discover projects with `bm_project(command="list")`. + ## PARAMETERS - **query** (string | null, optional, default: None) — What to search for. Omit to search by filters alone. @@ -68,7 +74,7 @@ The shell counterpart is grep(1). - **page** (integer, optional, default: 1) — Page number. - **page_size** (integer, optional, default: 10) — Results per page (1-100). - **output_format** (optional, default: "text") -- **project** (string | null, optional, default: None) — Project name, 'workspace/project', or project external id. With multiple addressable projects, scope note and search calls explicitly with this parameter or a project-qualified target. +- **project** (string | null, optional, default: None) — Project name, 'workspace/project', or external id. Required for one-project operations; search may instead use `projects` or `all_projects=true`. Project discovery needs no scope. ## EXAMPLES @@ -82,6 +88,9 @@ bm_search(query="launch", note_types=["plan"], compact=True, project="demo") # → Results for 'launch' in project 'demo': # - plans/launch-plan.md | launch-plan | score 1.212 +bm_search(query="launch", mode="text", projects=["demo", "team/research"]) +bm_search(query="launch", mode="text", all_projects=True) + bm_search(query="release", mode="text", page_size=1, output_format="json", project="demo") # → {"results": [{"title": "release-checklist", "file_path": "plans/release-checklist.md", # ...}], "current_page": 1, "page_size": 1, "total": 2, "has_more": true} diff --git a/src/basic_memory/man/man3/bm-write(3).md b/src/basic_memory/man/man3/bm-write(3).md index d7b822fb0..715613283 100644 --- a/src/basic_memory/man/man3/bm-write(3).md +++ b/src/basic_memory/man/man3/bm-write(3).md @@ -18,9 +18,9 @@ verified: 0.24.1 mcp ## SYNOPSIS ``` -bm_write(content, identifier=None, title=None, directory=None, +bm_write(content, project, identifier=None, title=None, directory=None, note_type="note", tags=None, metadata=None, overwrite=None, - expected_checksum=None, output_format="text", project=None) + expected_checksum=None, output_format="text") ``` ## DESCRIPTION @@ -46,6 +46,7 @@ observations and relations with bm_context. ## PARAMETERS - **content** (string, required) — The note's Markdown. Saved as given; it may start with frontmatter. +- **project** (string, required) — Required project name, 'workspace/project', or project external id. Discover projects with bm_project(command='list'). Paths are relative to this project; a qualified path must agree with it. - **identifier** (string | null, optional, default: None) — File path for the note, e.g. 'notes/plan.md'; '.md' is added when missing. '/path' writes into another project. Use instead of title + directory. - **title** (string | null, optional, default: None) — Note title. With `directory`, it also names the file. With `identifier`, it is used when the content has no frontmatter title. - **directory** (string | null, optional, default: None) — Folder for a note addressed by title, e.g. 'meetings'; '/' is the root. @@ -55,7 +56,6 @@ observations and relations with bm_context. - **overwrite** (boolean | null, optional, default: None) — Replace a note that already exists. Default: the write_note_overwrite_default setting (false unless changed). - **expected_checksum** (string | null, optional, default: None) — Replace the note only while it is still this revision (the checksum from bm_read). Implies overwrite=true. - **output_format** (optional, default: "text") -- **project** (string | null, optional, default: None) — Project name, 'workspace/project', or project external id. With multiple addressable projects, scope note and search calls explicitly with this parameter or a project-qualified target. ## EXAMPLES @@ -75,8 +75,8 @@ bm_write(title="Release Checklist", directory="plans", bm_write(identifier="plans/launch-plan.md", content="# again", project="demo") # → error: ALREADY_EXISTS: A note already exists at 'plans/launch-plan.md'. Nothing was written. -# Try instead: bm_edit(identifier='plans/launch-plan.md', command='append', content='...') -# to add to it, or bm_write(..., overwrite=true) to replace it +# Try instead: bm_edit(identifier='plans/launch-plan.md', command='append', content='...', project='demo') +# to add to it, or bm_write(..., project='demo', overwrite=true) to replace it ``` ## GOTCHAS diff --git a/src/basic_memory/mcp/directory_listing.py b/src/basic_memory/mcp/directory_listing.py index 61bec8590..7bb616785 100644 --- a/src/basic_memory/mcp/directory_listing.py +++ b/src/basic_memory/mcp/directory_listing.py @@ -1,8 +1,8 @@ """Directory listings: the project mount view and the text rendering of a page. -The mount view lists the addressable projects as directories, so `bm_list("/")` -doubles as project discovery. The text formatter renders any listing page the -same way, with the next-page call when more pages exist. +The legacy mount view lists addressable projects as directories. The bm_* surface +discovers projects with bm_project and requires scope on bm_list. The text +formatter renders any listing page with the next-page call when more pages exist. """ from datetime import datetime diff --git a/src/basic_memory/mcp/note_targets.py b/src/basic_memory/mcp/note_targets.py index 391b990c5..27d7e3021 100644 --- a/src/basic_memory/mcp/note_targets.py +++ b/src/basic_memory/mcp/note_targets.py @@ -166,7 +166,7 @@ async def resolve_note( raise refusal( "INVALID_ARGUMENTS", f"'{identifier}' names a project, not a note.", - try_instead=f"bm_list(path='{identifier.rstrip('/')}/')", + try_instead=f"bm_list(path='/', project={target.project.external_id!r})", output_format=output_format, ) @@ -178,13 +178,18 @@ async def resolve_note( match answer.status_code if answer is not None else None: case 404 if expected_checksum is not None: raise revision_conflict( - identifier, None, unchanged=unchanged, output_format=output_format + identifier, + None, + unchanged=unchanged, + output_format=output_format, + project=target.project.external_id, ) from error case 404: raise refusal( "NOT_FOUND", f"No note matches '{identifier}' in project '{target.project.name}'.", - try_instead=try_instead or f"bm_search(query='{identifier}')", + try_instead=try_instead + or f"bm_search(query={identifier!r}, project={target.project.external_id!r})", output_format=output_format, ) from error # Several notes match exactly (two notes with one title); the API's diff --git a/src/basic_memory/mcp/prompts/continue_conversation.py b/src/basic_memory/mcp/prompts/continue_conversation.py index 44d3450ac..d7d8ca02b 100644 --- a/src/basic_memory/mcp/prompts/continue_conversation.py +++ b/src/basic_memory/mcp/prompts/continue_conversation.py @@ -48,10 +48,16 @@ async def continue_conversation( """ logger.info(f"Continuing session, topic: {topic}, timeframe: {timeframe}") + # Prompts choose their default at the entrypoint; tool calls always name it. + project = await resolve_project_parameter(project=project, context=context) + if project is None: + return ( + "Choose a project with bm_project(command='list'), then continue this " + "conversation with an explicit project name or external id." + ) + if topic: # Use json format to get structured data for result counting and branching - # Choose the prompt's default explicitly before using the stricter search tool. - project = await resolve_project_parameter(project=project, context=context) result = await bm_search( query=topic, since=timeframe, project=project, context=context, output_format="json" ) @@ -90,8 +96,7 @@ async def continue_conversation( ## Next Steps """) - if project is not None: - prompt += f"\nPass `project={project!r}` on follow-up note and search calls.\n" + prompt += f"\nPass `project={project!r}` on follow-up note and search calls.\n" if topic and result_count > 0: prompt += dedent(f""" @@ -108,7 +113,7 @@ async def continue_conversation( prompt += dedent(f""" No previous context found for '{topic}'. - Try `bm_search` with related terms or check `bm_project(command="recent")`. If the user wants this + Try `bm_search` with related terms or check `bm_project(command="recent", project={project!r})`. If the user wants this topic tracked, offer to start a note with `bm_write`. """) else: diff --git a/src/basic_memory/mcp/prompts/recent_activity.py b/src/basic_memory/mcp/prompts/recent_activity.py index 7559f268f..3a4246b28 100644 --- a/src/basic_memory/mcp/prompts/recent_activity.py +++ b/src/basic_memory/mcp/prompts/recent_activity.py @@ -7,17 +7,19 @@ from typing import Annotated, Optional from loguru import logger +from fastmcp import Context from pydantic import Field from basic_memory.mcp.server import mcp +from basic_memory.mcp.project_context import resolve_project_parameter from basic_memory.mcp.tools.projects import bm_project @mcp.prompt( name="recent_activity", description=( - "Get recent activity from one project: the given one, else the default project. " - "Lists every project only when no default is set" + "Get recent activity from the given or configured default project. " + "Discover projects first when neither resolves." ), ) async def recent_activity_prompt( @@ -27,23 +29,20 @@ async def recent_activity_prompt( ] = "7d", project: Annotated[ Optional[str], - Field( - description=( - "Project to get activity from (None uses the default project; every " - "project is listed only when no default is set)" - ) - ), + Field(description="Project to get activity from (None uses the configured default)"), ] = None, + context: Context | None = None, ) -> str: """Get recent activity from one project. This prompt helps you see what's changed recently in the knowledge base. - With project=None it uses the active or default project, like the tool; - it shows activity across all projects only when no project resolves. + With project=None the prompt resolves the default before calling the scoped tool. + If no project resolves, it asks the caller to discover one first. Args: timeframe: How far back to look for activity (e.g. '1d', '1 week') project: Project to get activity from (None uses the default project) + context: MCP request context Returns: Formatted summary of recent activity @@ -51,16 +50,22 @@ async def recent_activity_prompt( timeframe = timeframe or "7d" logger.info(f"Getting recent activity, timeframe: {timeframe}, project: {project}") + project = await resolve_project_parameter(project=project, context=context) + if project is None: + return ( + "Choose a project with bm_project(command='list'), then request recent " + "activity with an explicit project name or external id." + ) + # Call the tool function - it returns a well-formatted string - activity_summary = await bm_project(command="recent", project=project, since=timeframe) + activity_summary = await bm_project( + command="recent", project=project, since=timeframe, context=context + ) # Build the prompt response # The tool already returns formatted markdown, so we use it directly # and add prompt-specific guidance - # A bare call resolves to the default project, or to every project when no - # default is configured. Only the tool knows which, and its summary states - # the scope, so the header names a project only when the caller gave one. - scope = f" from project '{project}'" if project else "" + scope = f" from project '{project}'" prompt_guidance = dedent(f""" # Recent Activity Context @@ -75,9 +80,9 @@ async def recent_activity_prompt( Based on this activity, you can: - 1. **Explore specific items** - Use `bm_read("permalink")` to dive deeper into any item - 2. **Search for related content** - Use `bm_search("topic")` to find connected knowledge - 3. **Build context** - Use `bm_context("memory://path")` to see relationships + 1. **Explore specific items** - Use `bm_read("permalink", project={project!r})` to dive deeper into any item + 2. **Search for related content** - Use `bm_search("topic", project={project!r})` to find connected knowledge + 3. **Build context** - Use `bm_context("memory://path", project={project!r})` to see relationships ## Capture Opportunity diff --git a/src/basic_memory/mcp/refusals.py b/src/basic_memory/mcp/refusals.py index 2bb6f27c7..2eeabb5c7 100644 --- a/src/basic_memory/mcp/refusals.py +++ b/src/basic_memory/mcp/refusals.py @@ -181,6 +181,7 @@ def revision_conflict( unchanged: str, output_format: OutputFormat, if_deleted: str = "bm_search to find where its content went", + project: str | None = None, ) -> ToolError: """A failed expected_checksum: the note changed since it was read, or it is gone. @@ -198,7 +199,9 @@ def revision_conflict( "REVISION_CONFLICT", f"'{address}' changed since you read it (current checksum {current_checksum}). {unchanged}", try_instead=( - f"bm_read(identifier='{address}'), then retry with " + f"bm_read(identifier={address!r}" + + (f", project={project!r}" if project is not None else "") + + "), then retry with " f"expected_checksum='{current_checksum}'" ), output_format=output_format, @@ -214,6 +217,7 @@ def note_change_failure( output_format: OutputFormat, occupied: str | None = None, subject: Literal["note", "directory"] = "note", + project: str | None = None, ) -> ToolError: """Explain a note change the API refused, or one whose outcome is unknown. @@ -223,11 +227,12 @@ def note_change_failure( """ def look_at(path: str) -> str: + scope = f", project={project!r}" if project is not None else "" match subject: case "note": - return f"bm_read(identifier='{path}')" + return f"bm_read(identifier={path!r}{scope})" case "directory": - return f"bm_list(path='{path}')" + return f"bm_list(path={path!r}{scope})" refused = api_refusal(error) if refused is None: @@ -242,7 +247,11 @@ def look_at(path: str) -> str: ) if refused.revision_conflict: return revision_conflict( - address, refused.current_checksum, unchanged=unchanged, output_format=output_format + address, + refused.current_checksum, + unchanged=unchanged, + output_format=output_format, + project=project, ) if occupied is not None and refused.code == "REVISION_CONFLICT": return refusal( diff --git a/src/basic_memory/mcp/resources/ai_assistant_guide.md b/src/basic_memory/mcp/resources/ai_assistant_guide.md index c4c258c37..6d5c6f250 100644 --- a/src/basic_memory/mcp/resources/ai_assistant_guide.md +++ b/src/basic_memory/mcp/resources/ai_assistant_guide.md @@ -6,10 +6,13 @@ plans, preferences, and connected reference material. ## Start usefully -1. Call `bm_project(command="recent")` to orient in the user's existing notes. -2. If no project is resolved, call `bm_project(command="list")` and ask which project to use. +1. Call `bm_project(command="list")` to discover projects; ask which to use if the user's + request does not identify one. +2. Call `bm_project(command="recent", project="")` to orient. 3. Preserve the selected route in later calls. Pass a returned `external_id` UUID as `project`, or use a workspace-qualified name (`workspace/project`), because names can collide across cloud workspaces. + Note, folder, context and schema tools always require `project`. Search requires `project`, + `projects`, or `all_projects=True`; project discovery and the bundled manual need no scope. 4. No recent activity does not prove the knowledge base is empty. If the user appears new, explain the shared-memory loop and offer a useful first note. Wait for agreement before creating it. diff --git a/src/basic_memory/mcp/server.py b/src/basic_memory/mcp/server.py index abb4a990e..a2535f25c 100644 --- a/src/basic_memory/mcp/server.py +++ b/src/basic_memory/mcp/server.py @@ -225,7 +225,7 @@ async def lifespan(app: FastMCP): "Basic Memory is the user's personal knowledge base: Markdown notes that persist " "across conversations and that both the user and their AI assistants can read and write.\n\n" "When a request may draw on the user's notes, use bm_search or " - 'bm_project(command="recent") before answering from memory. No recent activity does not ' + 'bm_project(command="recent", project="...") before answering from memory. No recent activity does not ' "prove a project is empty. If the knowledge base is empty, explain the shared-memory loop " "and offer a useful first note with bm_write; wait for agreement before writing. Do not write unprompted.\n\n" "Use bm_list for one folder, bm_find for recursive names or frontmatter inventories, " @@ -235,9 +235,9 @@ async def lifespan(app: FastMCP): "bm_write creates notes and explicitly overwrites them; bm_edit never creates missing notes. " "Use returned paths for subsequent reads and writes.\n\n" 'bm_project(command="list") discovers projects, grouped by workspace. Pass a project name, ' - "workspace/project, or external UUID through project. With multiple projects, qualify " - "paths or pass project; an explicit project must agree with a path prefix. " - 'bm_list(path="/") without a project constraint lists project mount points. ' + "workspace/project, or external UUID through the required project parameter on note, " + "folder, context and schema calls. A qualified path must agree with project. " + "Search requires project, projects, or all_projects=true. " "Calls do not remember a previous project selection.\n\n" "The installed tool schemas are authoritative. Most tools default to text; bm_context " 'defaults to JSON. Use output_format="json" when consuming structured fields. Failures ' diff --git a/src/basic_memory/mcp/tool_params.py b/src/basic_memory/mcp/tool_params.py index 05f6b6bd3..43daa5e66 100644 --- a/src/basic_memory/mcp/tool_params.py +++ b/src/basic_memory/mcp/tool_params.py @@ -12,7 +12,7 @@ from typing import Annotated, Any, Literal from uuid import UUID -from pydantic import AliasChoices, BeforeValidator, Field +from pydantic import AliasChoices, BeforeValidator, Field, StringConstraints from basic_memory.schemas.base import validate_timeframe from basic_memory.schemas.search import SearchItemType @@ -49,15 +49,30 @@ # --- Project --- ProjectParam = Annotated[ - str | None, + str, + StringConstraints(strip_whitespace=True, min_length=1), Field( # `project_id` stays accepted for callers written against the old tools; a # UUID in either spelling routes by external id (see parse_project). validation_alias=AliasChoices("project", "project_id"), description=( - "Project name, 'workspace/project', or project external id. With multiple " - "addressable projects, scope note and search calls explicitly with this " - "parameter or a project-qualified target." + "Required project name, 'workspace/project', or project external id. " + "Discover projects with bm_project(command='list'). Paths are relative " + "to this project; a qualified path must agree with it." + ), + ), +] + +# Discovery has no project yet; search may instead name several projects explicitly. +OptionalProjectParam = Annotated[ + str | None, + StringConstraints(strip_whitespace=True, min_length=1), + Field( + validation_alias=AliasChoices("project", "project_id"), + description=( + "Project name, 'workspace/project', or external id. Required for one-project " + "operations; search may instead use `projects` or `all_projects=true`. " + "Project discovery needs no scope." ), ), ] diff --git a/src/basic_memory/mcp/tools/chatgpt_tools.py b/src/basic_memory/mcp/tools/chatgpt_tools.py index e9ba20f81..ba4154936 100644 --- a/src/basic_memory/mcp/tools/chatgpt_tools.py +++ b/src/basic_memory/mcp/tools/chatgpt_tools.py @@ -18,7 +18,7 @@ resolve_project_parameter, ) from basic_memory.mcp.tools.read import bm_read -from basic_memory.mcp.refusals import Refusal +from basic_memory.mcp.refusals import Refusal, refusal from basic_memory.mcp.tools.ranked_search import bm_search from basic_memory.schemas.search import SearchResponse, SearchResult @@ -233,6 +233,8 @@ async def fetch( if detected is not None else await resolve_project_parameter(context=context) ) + if project is None: + raise refusal("INVALID_ARGUMENTS", "No project could be resolved for this document.") content = str( await bm_read( identifier=_identifier_for_bm_read(id), diff --git a/src/basic_memory/mcp/tools/context.py b/src/basic_memory/mcp/tools/context.py index 8d5c65da7..0c08c537f 100644 --- a/src/basic_memory/mcp/tools/context.py +++ b/src/basic_memory/mcp/tools/context.py @@ -89,7 +89,8 @@ async def bm_context( ), ] = 10, output_format: OutputFormat = "json", - project: ProjectParam = None, + *, + project: ProjectParam, context: Context | None = None, ) -> str | dict[str, Any]: """Build graph context from a starting note or pattern.""" diff --git a/src/basic_memory/mcp/tools/delete.py b/src/basic_memory/mcp/tools/delete.py index f7b622f96..904f96e45 100644 --- a/src/basic_memory/mcp/tools/delete.py +++ b/src/basic_memory/mcp/tools/delete.py @@ -70,7 +70,8 @@ async def bm_delete( ), ] = None, output_format: OutputFormat = "text", - project: ProjectParam = None, + *, + project: ProjectParam, context: Context | None = None, ) -> str | dict[str, Any]: """Delete one note or one directory.""" @@ -134,6 +135,7 @@ async def _delete_note( address=target.paths.path(note.file_path), unchanged="Nothing was deleted.", output_format=output_format, + project=target.project.external_id, ) from error file_path = target.paths.path(note.file_path) # Trigger: the note resolved, then was gone when the delete arrived. @@ -188,7 +190,9 @@ async def _delete_directory( "INVALID_ARGUMENTS", f"'{shown}' is a directory with {listing.total} entries at its top level. " "Deleting it removes everything under it.", - try_instead=f"bm_delete(path='{shown}', recursive=true)", + try_instead=( + f"bm_delete(path={shown!r}, recursive=true, project={target.project.external_id!r})" + ), output_format=output_format, ) @@ -204,6 +208,7 @@ async def _delete_directory( unchanged="Nothing was deleted.", output_format=output_format, subject="directory", + project=target.project.external_id, ) from error if deleted.total_files == 0: raise refusal( @@ -219,7 +224,9 @@ async def _delete_directory( + "; ".join( f"{target.paths.path(failure.path)}: {failure.error}" for failure in deleted.errors ), - try_instead=f"bm_list(path='{shown}') to see what is left", + try_instead=( + f"bm_list(path={shown!r}, project={target.project.external_id!r}) to see what is left" + ), output_format=output_format, ) if output_format == "json": diff --git a/src/basic_memory/mcp/tools/edit.py b/src/basic_memory/mcp/tools/edit.py index b186add4c..afda38954 100644 --- a/src/basic_memory/mcp/tools/edit.py +++ b/src/basic_memory/mcp/tools/edit.py @@ -121,7 +121,8 @@ async def bm_edit( ), ] = None, output_format: OutputFormat = "text", - project: ProjectParam = None, + *, + project: ProjectParam, context: Context | None = None, ) -> str | dict[str, Any]: """Edit one existing note.""" @@ -153,7 +154,10 @@ async def bm_edit( target, identifier, output_format=output_format, - try_instead=f"bm_write(identifier='{identifier}', content='...') to create it", + try_instead=( + f"bm_write(identifier={identifier!r}, content='...', project={project!r}) " + "to create it" + ), expected_checksum=expected_checksum, unchanged="Nothing was changed.", ) @@ -175,6 +179,7 @@ async def bm_edit( address=target.paths.path(note.file_path), unchanged="Nothing was changed.", output_format=output_format, + project=project, ) from error change = NoteChange.of(edited, action="edited", paths=target.paths) diff --git a/src/basic_memory/mcp/tools/find_files.py b/src/basic_memory/mcp/tools/find_files.py index b92cc6a26..b7bd0c839 100644 --- a/src/basic_memory/mcp/tools/find_files.py +++ b/src/basic_memory/mcp/tools/find_files.py @@ -80,7 +80,8 @@ async def bm_find( page: Page = 1, page_size: PageSize = 10, output_format: OutputFormat = "text", - project: ProjectParam = None, + *, + project: ProjectParam, context: Context | None = None, ) -> str | dict[str, Any]: """Find files by name, or notes by frontmatter.""" diff --git a/src/basic_memory/mcp/tools/listing.py b/src/basic_memory/mcp/tools/listing.py index 5f8eb8bda..1a647ca47 100644 --- a/src/basic_memory/mcp/tools/listing.py +++ b/src/basic_memory/mcp/tools/listing.py @@ -1,20 +1,17 @@ """bm_list: list one directory level. -`bm_list("/")` with no project lists the projects this session can address, so -listing doubles as project discovery; any other path lists one level of a project. -Recursive listing is bm_find's job. +Every listing names its project explicitly. Project discovery is bm_project's job; +recursive listing is bm_find's job. """ -import os from typing import Annotated, Any from fastmcp import Context from pydantic import AliasChoices, Field from basic_memory.mcp.clients import DirectoryClient -from basic_memory.mcp.directory_listing import format_listing_text, project_mount_listing +from basic_memory.mcp.directory_listing import format_listing_text from basic_memory.mcp.note_targets import open_project_target -from basic_memory.mcp.refusals import refusal from basic_memory.mcp.server import mcp from basic_memory.mcp.tool_params import ( Pagination, @@ -32,8 +29,8 @@ title="List folder", description=( "List one folder of a Basic Memory project: its subfolders, then its files with " - "title, date and id. `bm_list('/')` with no project lists the projects you can " - "address; '/path' lists inside another project. Filter files with `glob` " + "title, date and id. `project` is required; '/' lists its root. Discover projects " + "with bm_project(command='list'). Filter files with `glob` " "and order them with `sort`. For a recursive search by name or frontmatter, use " "bm_find." ), @@ -62,39 +59,11 @@ async def bm_list( page: Page = 1, page_size: PageSize = 10, output_format: OutputFormat = "text", - project: ProjectParam = None, + *, + project: ProjectParam, context: Context | None = None, ) -> str | dict[str, Any]: - """List one directory level, or the addressable projects at '/'.""" - # Trigger: the project root with no project named, by parameter or by the - # BASIC_MEMORY_MCP_PROJECT constraint. - # Why: projects are mount points (#1415); listing them in-band makes discovery - # the same call as browsing. - # Outcome: the projects as directory entries, each a routable '/' path. - if ( - project is None - and not os.environ.get("BASIC_MEMORY_MCP_PROJECT") - and not path.strip().strip("/") - ): - # The projects are folders, which `glob` and `sort` never apply to. - if glob is not None or sort is not None: - raise refusal( - "INVALID_ARGUMENTS", - "'/' lists projects; `glob` and `sort` apply to files in a folder.", - try_instead="bm_list(path='', glob=...), or bm_find to search by name", - output_format=output_format, - ) - mounts = await project_mount_listing(page=page, page_size=page_size, context=context) - if output_format == "json": - return mounts - text = format_listing_text( - DirectoryListResponse.model_validate(mounts), - heading="Projects:", - next_call=Pagination.of(mounts).next_call("bm_list", {"path": "/"}), - ) - note = mounts.get("note") - return f"{text}\n\nNote: {note}" if note else text - + """List one directory level within the required project.""" async with open_project_target(path, project, context, output_format=output_format) as target: list_path = f"/{target.route.path}" if target.route.stripped else path listing = await DirectoryClient(target.client, target.project.external_id).list( diff --git a/src/basic_memory/mcp/tools/move.py b/src/basic_memory/mcp/tools/move.py index 41a5c0ed2..5f34af02c 100644 --- a/src/basic_memory/mcp/tools/move.py +++ b/src/basic_memory/mcp/tools/move.py @@ -87,7 +87,8 @@ async def bm_move( ), ] = None, output_format: OutputFormat = "text", - project: ProjectParam = None, + *, + project: ProjectParam, context: Context | None = None, ) -> str | dict[str, Any]: """Move one note or one directory.""" @@ -213,6 +214,7 @@ async def _move_note( address=target.paths.path(note.file_path), unchanged="Nothing was moved.", occupied=target.paths.path(str(destination_path)), + project=target.project.external_id, output_format=output_format, ) from error @@ -312,13 +314,17 @@ async def _move_directory( occupied=target.paths.path(destination), output_format=output_format, subject="directory", + project=target.project.external_id, ) from error if moved.total_files == 0: raise refusal( "NOT_FOUND", f"No files under '{target.paths.path(source)}' in project '{target.project.name}'.", - try_instead=f"bm_list(path='{target.paths.path(source.rpartition('/')[0]) or '/'}')", + try_instead=( + f"bm_list(path={target.paths.path(source.rpartition('/')[0]) or '/'!r}, " + f"project={target.project.external_id!r})" + ), output_format=output_format, ) # The server may have kept an existing folder's spelling ('Archive' for @@ -349,7 +355,10 @@ async def _move_directory( f"Moved {moved.successful_moves} of {moved.total_files} files from " f"'{result['path']}' to '{result['destination']}'; {moved.failed_moves} failed: " + "; ".join(f"{failure['path']}: {failure['error']}" for failure in result["failed"]), - try_instead=f"bm_list(path='{result['destination']}') to see what moved", + try_instead=( + f"bm_list(path={result['destination']!r}, project={target.project.external_id!r}) " + "to see what moved" + ), output_format=output_format, ) if output_format == "json": diff --git a/src/basic_memory/mcp/tools/note_schemas.py b/src/basic_memory/mcp/tools/note_schemas.py index e99d9c883..116977000 100644 --- a/src/basic_memory/mcp/tools/note_schemas.py +++ b/src/basic_memory/mcp/tools/note_schemas.py @@ -69,7 +69,8 @@ async def bm_schema( ), ] = 0.25, output_format: OutputFormat = "text", - project: ProjectParam = None, + *, + project: ProjectParam, context: Context | None = None, ) -> ValidationReport | str | dict[str, Any]: """Validate, infer or diff note schemas.""" diff --git a/src/basic_memory/mcp/tools/projects.py b/src/basic_memory/mcp/tools/projects.py index fc94d7344..ac625f27c 100644 --- a/src/basic_memory/mcp/tools/projects.py +++ b/src/basic_memory/mcp/tools/projects.py @@ -21,7 +21,7 @@ OutputFormat, Page, PageSize, - ProjectParam, + OptionalProjectParam, Since, parse_project, routing_arguments, @@ -47,8 +47,7 @@ description=( "Basic Memory projects. `command`: list (projects, grouped by workspace); create " "(`name`, `path`, optional `set_default`, `workspace`); recent (what changed " - "lately: `since`, `items`, paging; `project` picks the project, else the default " - "project, and with no default every project)." + "lately in the required `project`: `since`, `items`, paging)." ), tags={"projects"}, annotations={ @@ -86,7 +85,7 @@ async def bm_project( page: Page = 1, page_size: PageSize = 10, output_format: OutputFormat = "text", - project: ProjectParam = None, + project: OptionalProjectParam = None, context: Context | None = None, ) -> str | dict[str, Any] | list[dict[str, Any]]: """List or create projects, or show what changed in them.""" @@ -110,6 +109,13 @@ async def bm_project( context=context, ) case "recent": + if project is None: + raise refusal( + "INVALID_ARGUMENTS", + "recent needs `project`, a project name, workspace/project or external id.", + try_instead="bm_project(command='list') to discover projects", + output_format=output_format, + ) project_name, project_id = routing_arguments(parse_project(project)) activity = await recent_activity_page( # recent_activity names whole notes "entity", the API's word. diff --git a/src/basic_memory/mcp/tools/ranked_search.py b/src/basic_memory/mcp/tools/ranked_search.py index a912b1828..dad3284a7 100644 --- a/src/basic_memory/mcp/tools/ranked_search.py +++ b/src/basic_memory/mcp/tools/ranked_search.py @@ -42,7 +42,7 @@ OutputFormat, Page, PageSize, - ProjectParam, + OptionalProjectParam, search_item_types, ) from basic_memory.mcp.workspace_project_index import get_cached_active_workspace @@ -92,7 +92,8 @@ def _parse_mode(value: Any) -> Any: "with `filters` (frontmatter), `note_types`, `items` (notes, observations, " "relations) and `since`. `lines` returns the matching lines of each hit with that " "many lines of context, like grep. `path` limits the search to a folder; " - "`identifier` searches one note. Read full notes with bm_read." + "`identifier` searches one note. Scope every search with `project` (one project), " + "`projects` (a list), or `all_projects=true`. Read full notes with bm_read." ), tags={"search"}, annotations={ @@ -187,7 +188,7 @@ async def bm_search( page: Page = 1, page_size: PageSize = 10, output_format: OutputFormat = "text", - project: ProjectParam = None, + project: OptionalProjectParam = None, context: Context | None = None, ) -> str | dict[str, Any]: """Search notes, observations and relations.""" @@ -266,6 +267,13 @@ async def bm_search( "`project` names one project; `projects` and `all_projects` name several. Give one.", output_format=output_format, ) + if not several_projects and project is None: + raise refusal( + "INVALID_ARGUMENTS", + "Search needs an explicit scope: `project`, `projects`, or `all_projects=true`.", + try_instead="bm_project(command='list') to discover projects", + output_format=output_format, + ) # max_matches bounds a line scan; ranked results have no matching lines to bound. if max_matches != DEFAULT_MAX_MATCHES and lines is None and identifier is None: raise refusal( @@ -610,7 +618,7 @@ async def _search_one_note( raise refusal( "UNSUPPORTED", f"'{note.file_path}' is not a Markdown note, so it has no lines to search.", - try_instead=f"bm_read(identifier='{note.file_path}')", + try_instead=f"bm_read(identifier={note.file_path!r}, project={project!r})", output_format=output_format, ) scan = scan_lines( diff --git a/src/basic_memory/mcp/tools/read.py b/src/basic_memory/mcp/tools/read.py index ce6b9a0e5..00455ce44 100644 --- a/src/basic_memory/mcp/tools/read.py +++ b/src/basic_memory/mcp/tools/read.py @@ -86,7 +86,8 @@ async def bm_read( Field(description="False returns only title, paths, checksum and updated_at."), ] = True, output_format: OutputFormat = "text", - project: ProjectParam = None, + *, + project: ProjectParam, context: Context | None = None, ) -> str | dict[str, Any] | ImageContent | EmbeddedResource: """Read one note or file.""" @@ -145,7 +146,7 @@ async def bm_read( "UNSUPPORTED", f"'{note.file_path}' is not a Markdown note; section, lines and " "max_tokens apply only to notes.", - try_instead=f"bm_read(identifier='{identifier}')", + try_instead=f"bm_read(identifier={identifier!r}, project={project!r})", output_format=output_format, ) response = await resource_client.read(note.external_id) diff --git a/src/basic_memory/mcp/tools/view_note.py b/src/basic_memory/mcp/tools/view_note.py index 8c3802e79..66f08cf63 100644 --- a/src/basic_memory/mcp/tools/view_note.py +++ b/src/basic_memory/mcp/tools/view_note.py @@ -7,6 +7,8 @@ from fastmcp import Context from basic_memory.mcp.tools.read import bm_read +from basic_memory.mcp.project_context import resolve_project_parameter +from basic_memory.mcp.refusals import refusal async def view_note( @@ -49,11 +51,19 @@ async def view_note( """ logger.debug(f"Viewing note: {identifier} in project: {project}") + resolved_project = project_id or await resolve_project_parameter(project, context=context) + if resolved_project is None: + raise refusal( + "INVALID_ARGUMENTS", + "View needs a project name or external id.", + try_instead="bm_project(command='list') to discover projects", + ) + # Call the existing bm_read logic (default output_format="text" returns str) content = str( await bm_read( identifier=identifier, - project=project_id or project, + project=resolved_project, context=context, ) ) diff --git a/src/basic_memory/mcp/tools/write.py b/src/basic_memory/mcp/tools/write.py index 72b4a9368..def490b65 100644 --- a/src/basic_memory/mcp/tools/write.py +++ b/src/basic_memory/mcp/tools/write.py @@ -151,7 +151,8 @@ async def bm_write( ), ] = None, output_format: OutputFormat = "text", - project: ProjectParam = None, + *, + project: ProjectParam, context: Context | None = None, ) -> str | dict[str, Any]: """Create or replace one note.""" @@ -160,14 +161,16 @@ async def bm_write( raise refusal( "INVALID_ARGUMENTS", "Give either `identifier` (a file path) or `title` + `directory`, not both.", - try_instead=f"bm_write(identifier='{directory.strip('/')}/.md', ...)", + try_instead=( + f"bm_write(identifier='{directory.strip('/')}/.md', project={project!r}, ...)" + ), output_format=output_format, ) if identifier is None and (title is None or directory is None): raise refusal( "INVALID_ARGUMENTS", "Say where the note goes: `identifier` (a file path) or `title` + `directory`.", - try_instead="bm_write(identifier='notes/plan.md', content='...')", + try_instead=f"bm_write(identifier='notes/plan.md', content='...', project={project!r})", output_format=output_format, ) # Trigger: the caller pinned a revision but did not say overwrite. @@ -238,6 +241,7 @@ async def bm_write( address=target.paths.path(note.file_path), unchanged="Nothing was written.", output_format=output_format, + project=project, ) from error # --- Outcomes --- @@ -252,8 +256,9 @@ async def bm_write( "ALREADY_EXISTS", f"A note already exists at '{shown}'. Nothing was written.", try_instead=( - f"bm_edit(identifier='{shown}', command='append', content='...') to " - "add to it, or bm_write(..., overwrite=true) to replace it" + f"bm_edit(identifier={shown!r}, command='append', content='...', " + f"project={project!r}) to add to it, or " + f"bm_write(..., project={project!r}, overwrite=true) to replace it" ), output_format=output_format, ) @@ -263,7 +268,7 @@ async def bm_write( "ALREADY_EXISTS", f"The note this path names has moved to '{shown}'. Nothing was written.", try_instead=( - f"bm_read(identifier='{shown}') to work on that note, or " + f"bm_read(identifier={shown!r}, project={project!r}) to work on that note, or " "overwrite=false to create a separate note at this path" ), output_format=output_format, @@ -277,6 +282,7 @@ async def bm_write( unchanged="Nothing was replaced.", if_deleted="bm_write without expected_checksum to create it", output_format=output_format, + project=project, ) case _: # pragma: no cover assert_never(outcome) @@ -306,7 +312,7 @@ async def bm_write( **change.as_json(), "similar_notes": [dataclasses.asdict(similar) for similar in similar_notes], } - return _format_text(change, similar_notes) + return _format_text(change, similar_notes, project=project) def _place_note( @@ -342,7 +348,10 @@ def _place_note( raise refusal( "INVALID_ARGUMENTS", f"'{identifier}' names a folder or project, not a note file.", - try_instead=f"bm_write(identifier='{identifier.rstrip('/')}/.md', ...)", + try_instead=( + f"bm_write(identifier='{identifier.rstrip('/')}/.md', " + f"project={target.project.external_id!r}, ...)" + ), output_format=output_format, ) # Trigger: the name has an extension other than '.md' or '.markdown' ('data.json', @@ -358,7 +367,8 @@ def _place_note( "'.markdown' notes.", try_instead=( "bm_write(identifier=" - f"'{target.paths.path(str(path.with_name(path.name + MARKDOWN_SUFFIX)))}')" + f"'{target.paths.path(str(path.with_name(path.name + MARKDOWN_SUFFIX)))}', " + f"project={target.project.external_id!r}, content='...')" ), output_format=output_format, ) @@ -428,7 +438,7 @@ async def _similar_notes( return [] -def _format_text(change: NoteChange, similar_notes: list[SimilarNote]) -> str: +def _format_text(change: NoteChange, similar_notes: list[SimilarNote], *, project: str) -> str: """The text result: what was written, where, and the checksum to pass back.""" lines = change.text_lines() if similar_notes: @@ -436,8 +446,9 @@ def _format_text(change: NoteChange, similar_notes: list[SimilarNote]) -> str: format_similar_notes_section( similar_notes, same_topic=lambda closest: ( - f"`bm_edit(identifier='{closest}', command='append', content='...')`, " - f"then `bm_delete(identifier='{change.file_path}')`" + f"`bm_edit(identifier={closest!r}, command='append', content='...', " + f"project={project!r})`, then " + f"`bm_delete(identifier={change.file_path!r}, project={project!r})`" ), reference=lambda note: note.file_path, ) diff --git a/tests/mcp/test_first_connect_onboarding.py b/tests/mcp/test_first_connect_onboarding.py index b2a492af2..4c2d6718f 100644 --- a/tests/mcp/test_first_connect_onboarding.py +++ b/tests/mcp/test_first_connect_onboarding.py @@ -26,7 +26,7 @@ def test_server_sets_first_connect_instructions(): assert instructions is not None # Orients the model to what Basic Memory is and points at the first-note action. assert "Basic Memory" in instructions - assert 'bm_project(command="recent")' in instructions + assert 'bm_project(command="recent", project=' in instructions assert "bm_write" in instructions assert "https://docs.basicmemory.com/llms.txt" in instructions assert "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/raw/...md" in instructions diff --git a/tests/mcp/test_note_targets.py b/tests/mcp/test_note_targets.py index 39a585e8c..1c377590f 100644 --- a/tests/mcp/test_note_targets.py +++ b/tests/mcp/test_note_targets.py @@ -67,7 +67,7 @@ async def test_a_missing_note_is_a_not_found_refusal(client, test_project): message = str(refused.value) assert message.startswith("NOT_FOUND: No note matches 'notes/Nope.md'") - assert "Try instead: bm_search(query='notes/Nope.md')" in message + assert f"bm_search(query='notes/Nope.md', project='{test_project.external_id}')" in message @pytest.mark.asyncio @@ -78,7 +78,9 @@ async def test_a_missing_note_refusal_in_json(client, test_project): payload = json.loads(str(refused.value)) assert payload["error"] == "NOT_FOUND" - assert payload["try_instead"] == "bm_search(query='notes/Nope.md')" + assert payload["try_instead"] == ( + f"bm_search(query='notes/Nope.md', project='{test_project.external_id}')" + ) @pytest.mark.asyncio @@ -90,7 +92,7 @@ async def test_a_bare_project_name_is_not_a_note(client, test_project): message = str(refused.value) assert message.startswith("INVALID_ARGUMENTS:") - assert f"bm_list(path='{test_project.name}/')" in message + assert f"bm_list(path='/', project='{test_project.external_id}')" in message @pytest.mark.asyncio diff --git a/tests/mcp/test_prompts.py b/tests/mcp/test_prompts.py index 02809a1a7..f45206c54 100644 --- a/tests/mcp/test_prompts.py +++ b/tests/mcp/test_prompts.py @@ -85,7 +85,7 @@ async def test_recent_activity_prompt_discovery_mode(client, test_project, test_ result = await recent_activity_prompt(timeframe="1w") # pyright: ignore [reportGeneralTypeIssues] assert "Recent Activity Context" in result # pyright: ignore [reportOperatorIssue] - assert "showing recent activity." in result # pyright: ignore [reportOperatorIssue] + assert f"showing recent activity from project '{test_project.name}'." in result assert "Next Steps" in result # pyright: ignore [reportOperatorIssue] assert "bm_write" in result # pyright: ignore [reportOperatorIssue] diff --git a/tests/mcp/test_recent_activity_prompt_modes.py b/tests/mcp/test_recent_activity_prompt_modes.py index 7a8ba1536..af19df83f 100644 --- a/tests/mcp/test_recent_activity_prompt_modes.py +++ b/tests/mcp/test_recent_activity_prompt_modes.py @@ -11,19 +11,12 @@ @pytest.mark.asyncio -async def test_recent_activity_prompt_discovery_mode(monkeypatch): - """Test prompt in discovery mode (no project specified).""" - # The tool returns a formatted string in discovery mode - tool_output = """## Recent Activity Summary (7d) +async def test_recent_activity_prompt_resolves_default_scope(monkeypatch, config_manager): + """An omitted prompt scope resolves the default before dispatching the tool.""" + default_project = config_manager.config.default_project + tool_output = f"""## Recent Activity: {default_project} (7d) -**Most Active Project:** project-alpha (5 items) -- 🔧 **Latest:** API Design Decision (2 hours ago) -- 📋 **Focus areas:** decisions, specs - -**Other Active Projects:** -- **project-beta** (3 items) - -**Summary:** 2 active projects, 8 recent items +- API Design Decision (2 hours ago) """ async def fake_fn(**_kwargs): @@ -34,20 +27,19 @@ async def fake_fn(**_kwargs): out = await recent_activity_prompt(timeframe="7d", project=None) # pyright: ignore[reportGeneralTypeIssues] # Should contain the tool output - assert "Recent Activity Summary (7d)" in out - assert "Most Active Project" in out + assert f"Recent Activity: {default_project} (7d)" in out + assert "API Design Decision" in out # Should contain prompt guidance assert "Recent Activity Context" in out assert "Next Steps" in out assert "Capture Opportunity" in out - # Discovery mode has no project; the guidance must not invent a "default" project name. + # Guidance carries the resolved route rather than a made-up project named default. assert 'project="default"' not in out - # A bare call may reach the default project or every project; the header must - # not assert either scope, since the tool output states which one applied. assert "all projects" not in out assert "default project" not in out - assert "showing recent activity." in out + assert f"showing recent activity from project '{default_project}'." in out + assert f"project='{default_project}'" in out @pytest.mark.asyncio @@ -100,7 +92,7 @@ async def fake_fn(**kwargs): @pytest.mark.asyncio -async def test_recent_activity_prompt_defaults_timeframe(monkeypatch): +async def test_recent_activity_prompt_defaults_timeframe(monkeypatch, config_manager): """Prompt should fall back to 7d when timeframe omitted or falsy.""" captured_kwargs = {} @@ -113,4 +105,4 @@ async def fake_fn(**kwargs): await recent_activity_prompt(timeframe=cast(Any, None), project=None) assert captured_kwargs["since"] == "7d" - assert captured_kwargs["project"] is None + assert captured_kwargs["project"] == config_manager.config.default_project diff --git a/tests/mcp/test_required_project.py b/tests/mcp/test_required_project.py new file mode 100644 index 000000000..643978955 --- /dev/null +++ b/tests/mcp/test_required_project.py @@ -0,0 +1,178 @@ +"""Project scope is explicit at the MCP boundary, including single-project sessions.""" + +import ast +import importlib +import json +from typing import Any +from unittest.mock import AsyncMock + +import pytest +from fastmcp import Client, FastMCP +from fastmcp.exceptions import ToolError + +from basic_memory.mcp import tools +from basic_memory.mcp.refusals import Refusal +from basic_memory.mcp.tools import chatgpt_tools + +SCOPED_TOOLS = { + "bm_read": {"identifier": "notes/plan.md"}, + "bm_write": {"identifier": "notes/plan.md", "content": "# Plan"}, + "bm_edit": {"identifier": "notes/plan.md", "command": "append", "content": "tail"}, + "bm_move": {"identifier": "notes/plan.md", "destination": "archive/plan.md"}, + "bm_delete": {"identifier": "notes/plan.md"}, + "bm_list": {"path": "/"}, + "bm_find": {"path": "/"}, + "bm_context": {"identifier": "notes/plan.md"}, + "bm_schema": {"command": "validate"}, +} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("name", SCOPED_TOOLS) +async def test_project_is_required_and_nonnullable_in_advertised_schema(name: str): + server = FastMCP("project-scope") + server.tool(getattr(tools, name)) + async with Client(server) as client: + (tool,) = await client.list_tools() + assert "project" in tool.input_schema["required"] + project = tool.input_schema["properties"]["project"] + assert project["type"] == "string" + assert project["minLength"] == 1 + assert "default" not in project + + +@pytest.mark.asyncio +@pytest.mark.parametrize("name", SCOPED_TOOLS) +@pytest.mark.parametrize("scope", [{}, {"project": None}, {"project": ""}, {"project": " "}]) +async def test_invalid_scope_is_rejected_before_any_project_io(name: str, scope: dict[str, Any]): + # No app, database or server lifespan: these calls must fail at validation, + # even if a constrained server or a qualified identifier could infer a project. + server = FastMCP("project-scope") + server.tool(getattr(tools, name)) + async with Client(server) as client: + result = await client.call_tool(name, {**SCOPED_TOOLS[name], **scope}, raise_on_error=False) + assert result.is_error + assert "project" in str(result.content) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("arguments", [{"query": "plan"}, {"query": "memory://research/plan"}]) +async def test_single_project_search_requires_scope(arguments): + with pytest.raises(ToolError, match="Search needs an explicit scope"): + await tools.bm_search(**arguments) + + +@pytest.mark.asyncio +async def test_explicit_project_id_alias_reads_the_same_note(client, test_project): + await tools.bm_write(identifier="notes/plan.md", content="# Plan", project=test_project.name) + server = FastMCP("project-scope") + server.tool(tools.bm_read) + async with Client(server) as mcp_client: + result = await mcp_client.call_tool( + "bm_read", + {"identifier": "notes/plan.md", "project_id": str(test_project.external_id)}, + ) + assert "# Plan" in str(result.content) + + +@pytest.mark.asyncio +async def test_discovery_and_bundled_manual_need_no_project(client, test_project): + projects = await tools.bm_project(command="list", output_format="json") + assert isinstance(projects, dict) + assert test_project.name in {project["name"] for project in projects["projects"]} + manual = await tools.bm_man(page="bm-read(3)") + assert "bm_read" in str(manual) + + +@pytest.mark.asyncio +async def test_required_scope_keeps_same_named_folders_inside_selected_project( + client, test_project, second_project +): + await tools.bm_write( + identifier="notes/plan.md", content="First project's plan", project=test_project.name + ) + await tools.bm_write( + identifier="notes/plan.md", content="Second project's plan", project=second_project.name + ) + first = await tools.bm_read("notes/plan.md", project=test_project.name) + second = await tools.bm_read("notes/plan.md", project=str(second_project.external_id)) + assert "First project's plan" in str(first) and "Second project's plan" not in str(first) + assert "Second project's plan" in str(second) and "First project's plan" not in str(second) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("scope", ["projects", "all_projects"]) +async def test_search_explicit_multi_project_scope_is_preserved(client, test_project, scope): + await tools.bm_write( + identifier="notes/plan.md", content="uniquebenchscopeword", project=test_project.name + ) + result = await tools.bm_search( + query="uniquebenchscopeword", + mode="text", + output_format="json", + projects=[test_project.name] if scope == "projects" else None, + all_projects=scope == "all_projects", + ) + assert isinstance(result, dict) + assert result["results"] + + +@pytest.mark.asyncio +async def test_conflict_recovery_call_includes_scope_and_can_be_dispatched(client, test_project): + await tools.bm_write(identifier="notes/plan.md", content="# Plan", project=test_project.name) + with pytest.raises(Refusal) as conflict: + await tools.bm_edit( + identifier="notes/plan.md", + command="append", + content="tail", + expected_checksum="stale", + project=test_project.name, + ) + hint = conflict.value.try_instead + assert hint is not None + call = ast.parse(hint.split(", then retry")[0], mode="eval").body + assert isinstance(call, ast.Call) + arguments = {argument.arg: ast.literal_eval(argument.value) for argument in call.keywords} + assert arguments["project"] == test_project.name + server = FastMCP("project-scope") + server.tool(tools.bm_read) + async with Client(server) as mcp_client: + result = await mcp_client.call_tool("bm_read", arguments) + assert "# Plan" in str(result.content) + + +@pytest.mark.asyncio +async def test_legacy_view_reports_unresolved_scope(monkeypatch): + view_module = importlib.import_module("basic_memory.mcp.tools.view_note") + monkeypatch.setattr(view_module, "resolve_project_parameter", AsyncMock(return_value=None)) + with pytest.raises(ToolError, match="View needs a project"): + await view_module.view_note("Plan") + + +@pytest.mark.asyncio +async def test_chatgpt_fetch_reports_unresolved_scope(monkeypatch): + monkeypatch.setattr(chatgpt_tools, "is_openai_mcp_client", AsyncMock(return_value=True)) + monkeypatch.setattr( + chatgpt_tools, "detect_project_from_identifier_prefix", AsyncMock(return_value=None) + ) + monkeypatch.setattr(chatgpt_tools, "resolve_project_parameter", AsyncMock(return_value=None)) + (result,) = await chatgpt_tools.fetch("Plan") + assert json.loads(result["text"])["metadata"]["error"] == "INVALID_ARGUMENTS" + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("module_name", "prompt_name"), + [ + ("continue_conversation", "continue_conversation"), + ("recent_activity", "recent_activity_prompt"), + ], +) +async def test_prompts_discover_before_calling_tools_when_no_project_resolves( + monkeypatch, module_name, prompt_name +): + module = importlib.import_module(f"basic_memory.mcp.prompts.{module_name}") + monkeypatch.setattr(module, "resolve_project_parameter", AsyncMock(return_value=None)) + result = await getattr(module, prompt_name)() + assert "bm_project(command='list')" in result + assert "explicit project" in result diff --git a/tests/mcp/test_resources.py b/tests/mcp/test_resources.py index 266ed688c..bdb9653ba 100644 --- a/tests/mcp/test_resources.py +++ b/tests/mcp/test_resources.py @@ -19,7 +19,7 @@ def test_ai_assistant_guide_exists(): guide = ai_assistant_guide() assert "# AI Assistant Guide" in guide - assert 'bm_project(command="recent")' in guide + assert 'bm_project(command="recent", project=' in guide assert "`external_id` UUID as `project`" in guide assert "directory" in guide assert "https://docs.basicmemory.com/llms.txt" in guide diff --git a/tests/mcp/test_tool_bm_context.py b/tests/mcp/test_tool_bm_context.py index e73cf66c9..de91c6b9a 100644 --- a/tests/mcp/test_tool_bm_context.py +++ b/tests/mcp/test_tool_bm_context.py @@ -102,7 +102,7 @@ async def test_project_qualified_start_returns_qualified_paths(client, test_proj await _seed(test_project.name) prefix = test_project.permalink - graph = await context_json(identifier=f"{prefix}/graph/node-a") + graph = await context_json(identifier=f"{prefix}/graph/node-a", project=test_project.name) (result,) = graph["results"] paths = [result["primary_result"]["file_path"]] @@ -117,7 +117,9 @@ async def test_project_qualified_text_names_qualified_paths(client, test_project await _seed(test_project.name) prefix = test_project.permalink - text = await bm_context(identifier=f"{prefix}/graph/node-a", output_format="text") + text = await bm_context( + identifier=f"{prefix}/graph/node-a", output_format="text", project=test_project.name + ) assert isinstance(text, str) assert f"path: {prefix}/graph/Node A.md" in text diff --git a/tests/mcp/test_tool_bm_delete.py b/tests/mcp/test_tool_bm_delete.py index d79db7ba4..2726791bc 100644 --- a/tests/mcp/test_tool_bm_delete.py +++ b/tests/mcp/test_tool_bm_delete.py @@ -64,7 +64,7 @@ async def test_project_qualified_identifier(client, test_project): await _note(test_project.name) prefix = test_project.permalink - text = await bm_delete(identifier=f"{prefix}/notes/plan.md") + text = await bm_delete(identifier=f"{prefix}/notes/plan.md", project=test_project.name) assert text == f"Deleted {prefix}/notes/plan.md" @@ -169,7 +169,7 @@ async def refused(*_args: Any, **_kwargs: Any) -> None: with pytest.raises(ToolError, match="^LOCKED: A note is locked. Nothing was deleted."): await bm_delete(path="drafts", recursive=True, project=test_project.name) # A directory is looked at with bm_list, not bm_read. - with pytest.raises(ToolError, match=r"bm_list\(path='drafts'\)"): + with pytest.raises(ToolError, match=r"bm_list\(path='drafts', project="): await bm_delete(path="drafts", recursive=True, project=test_project.name) diff --git a/tests/mcp/test_tool_bm_edit.py b/tests/mcp/test_tool_bm_edit.py index 0529fac3e..efded57b7 100644 --- a/tests/mcp/test_tool_bm_edit.py +++ b/tests/mcp/test_tool_bm_edit.py @@ -298,12 +298,13 @@ async def test_refusal_guidance_keeps_the_project_prefix(client, test_project): await _seed(test_project.name) prefix = test_project.permalink - with pytest.raises(ToolError, match=f"bm_read\\(identifier='{prefix}/notes/plan.md'\\)"): + with pytest.raises(ToolError, match=f"bm_read\\(identifier='{prefix}/notes/plan.md', project="): await bm_edit( identifier=f"{prefix}/notes/plan.md", command="append", content="x", expected_checksum="stale", + project=test_project.name, ) diff --git a/tests/mcp/test_tool_bm_list.py b/tests/mcp/test_tool_bm_list.py index e399133a1..a65b9d640 100644 --- a/tests/mcp/test_tool_bm_list.py +++ b/tests/mcp/test_tool_bm_list.py @@ -1,4 +1,4 @@ -"""bm_list: project discovery at '/', one-level folder listings, round-trip paths (#1830). +"""bm_list: explicitly scoped one-level folder listings and round-trip paths (#1919). These run the real ASGI stack through the shared `client` fixture. """ @@ -31,17 +31,17 @@ async def _seed(project_name: str) -> None: ) -# --- Project discovery --- +# --- Root listings --- @pytest.mark.asyncio -async def test_root_without_a_project_lists_projects(client, test_project): - text = await list_text(path="/") - payload = await list_json(path="/") +async def test_root_lists_the_named_project(client, test_project): + await _seed(test_project.name) + text = await list_text(path="/", project=test_project.name) + payload = await list_json(path="/", project=test_project.name) - assert text.startswith("Projects:") - assert test_project.name in text - assert f"/{test_project.permalink}" in {node["directory_path"] for node in payload["nodes"]} + assert text.startswith("Contents of '/':") + assert "notes" in {node["name"] for node in payload["nodes"]} # --- Folder listings --- @@ -95,7 +95,7 @@ async def test_empty_folder(client, test_project): async def test_project_qualified_listing_returns_qualified_paths(client, test_project): await _seed(test_project.name) - payload = await list_json(path=f"{test_project.permalink}/notes") + payload = await list_json(path=f"{test_project.permalink}/notes", project=test_project.name) file_paths = {node["file_path"] for node in payload["nodes"] if node["type"] == "file"} assert f"{test_project.permalink}/notes/Alpha.md" in file_paths @@ -105,7 +105,9 @@ async def test_project_qualified_listing_returns_qualified_paths(client, test_pr async def test_bm_read_returns_the_path_it_was_given(client, test_project): await _seed(test_project.name) - payload = await bm_read(f"{test_project.permalink}/notes/Alpha.md", output_format="json") + payload = await bm_read( + f"{test_project.permalink}/notes/Alpha.md", output_format="json", project=test_project.name + ) assert isinstance(payload, dict) assert payload["file_path"] == f"{test_project.permalink}/notes/Alpha.md" @@ -122,7 +124,9 @@ async def test_listing_outside_the_project_is_refused(client, test_project): @pytest.mark.asyncio @pytest.mark.parametrize("arguments", [{"glob": "*.md"}, {"sort": "title_asc"}]) -async def test_project_listing_refuses_file_filters(client, test_project, arguments): - """'/' lists projects, which a file glob or sort cannot filter.""" - with pytest.raises(ToolError, match="^INVALID_ARGUMENTS: '/' lists projects"): - await bm_list(path="/", **arguments) +async def test_project_root_accepts_file_filters(client, test_project, arguments): + """'/' is now the named project's root; its files accept globs and sorting.""" + await _seed(test_project.name) + await write_note(title="Root", directory="", content="# Root", project=test_project.name) + payload = await list_json(path="/", project=test_project.name, **arguments) + assert "Root.md" in {node["name"] for node in payload["nodes"]} diff --git a/tests/mcp/test_tool_bm_move.py b/tests/mcp/test_tool_bm_move.py index e6a1201ba..bfd8ff706 100644 --- a/tests/mcp/test_tool_bm_move.py +++ b/tests/mcp/test_tool_bm_move.py @@ -122,7 +122,9 @@ async def test_project_qualified_destination(client, test_project): prefix = test_project.permalink result = await move_json( - identifier=f"{prefix}/notes/plan.md", destination=f"{prefix}/archive/plan.md" + identifier=f"{prefix}/notes/plan.md", + destination=f"{prefix}/archive/plan.md", + project=test_project.name, ) assert result["file_path"] == f"{prefix}/archive/plan.md" @@ -136,7 +138,9 @@ async def test_destination_prefix_matches_any_spelling_of_the_project(client, te prefix = test_project.permalink result = await move_json( - identifier=f"{prefix}/notes/plan.md", destination=f"{prefix.upper()}/archive/" + identifier=f"{prefix}/notes/plan.md", + destination=f"{prefix.upper()}/archive/", + project=test_project.name, ) assert result["file_path"] == f"{prefix}/archive/plan.md" @@ -149,8 +153,12 @@ async def test_project_root_destination(client, test_project): await _note(test_project.name, "archive/drafts/a.md") prefix = test_project.permalink - note = await move_json(identifier=f"{prefix}/notes/plan.md", destination=f"{prefix}/") - directory = await move_json(path=f"{prefix}/archive/drafts", destination=f"{prefix}/") + note = await move_json( + identifier=f"{prefix}/notes/plan.md", destination=f"{prefix}/", project=test_project.name + ) + directory = await move_json( + path=f"{prefix}/archive/drafts", destination=f"{prefix}/", project=test_project.name + ) assert note["file_path"] == f"{prefix}/plan.md" assert directory["moved_files"] == [f"{prefix}/drafts/a.md"] @@ -209,7 +217,9 @@ async def lost(*_args: Any, **_kwargs: Any) -> None: raise error monkeypatch.setattr(KnowledgeClient, "move_directory", lost) - with pytest.raises(ToolError, match=r"(?s)^OUTCOME_UNKNOWN: .*bm_list\(path='archive'\)"): + with pytest.raises( + ToolError, match=r"(?s)^OUTCOME_UNKNOWN: .*bm_list\(path='archive', project=" + ): await bm_move(path="drafts", destination="archive", project=test_project.name) @@ -367,8 +377,10 @@ async def deleted(*_args: Any, **_kwargs: Any) -> None: async def test_missing_directory_hint_is_qualified(client, test_project): prefix = test_project.permalink - with pytest.raises(ToolError, match=f"bm_list\\(path='{prefix}'\\)"): - await bm_move(path=f"{prefix}/nope", destination=f"{prefix}/archive") + with pytest.raises(ToolError, match=f"bm_list\\(path='{prefix}', project="): + await bm_move( + path=f"{prefix}/nope", destination=f"{prefix}/archive", project=test_project.name + ) @pytest.mark.parametrize( diff --git a/tests/mcp/test_tool_bm_project.py b/tests/mcp/test_tool_bm_project.py index 4f5bb29af..518640ab9 100644 --- a/tests/mcp/test_tool_bm_project.py +++ b/tests/mcp/test_tool_bm_project.py @@ -1,6 +1,5 @@ """bm_project and bm_schema: one name per group, commands delegate (#1832).""" -import importlib from typing import Any import pytest @@ -120,34 +119,10 @@ async def test_recent_json_carries_paging(client, test_project): @pytest.mark.asyncio -async def test_recent_discovery_keeps_activity_beside_unindexed_guidance( - client, test_project, second_project, monkeypatch -): - """One unindexed project does not hide the activity found in the others.""" - await bm_write(identifier="notes/fresh.md", content="# fresh", project=test_project.name) - - async def no_project(*_args: Any, **_kwargs: Any) -> None: - return None - - async def only_second_unindexed(_client: Any, project: Any) -> str | None: - return ( - f"'{project.name}' has never been indexed" - if project.name == second_project.name - else None - ) - - # The tools package re-exports the function under the module's name. - recent_activity_module = importlib.import_module("basic_memory.mcp.tools.recent_activity") - monkeypatch.setattr(recent_activity_module, "resolve_project_parameter", no_project) - monkeypatch.setattr(recent_activity_module, "project_index_required", only_second_unindexed) - - payload = await bm_project(command="recent", output_format="json") - text = await bm_project(command="recent") - - assert isinstance(payload, dict) and isinstance(text, str) - assert any(row["title"] == "fresh" for row in payload["results"]) - assert payload["guidance"] == f"'{second_project.name}' has never been indexed" - assert "fresh" in text and f"'{second_project.name}' has never been indexed" in text +@pytest.mark.parametrize("output_format", ["text", "json"]) +async def test_recent_requires_project(output_format): + with pytest.raises(ToolError, match="recent needs `project`"): + await bm_project(command="recent", output_format=output_format) @pytest.mark.asyncio diff --git a/tests/mcp/test_tool_bm_read.py b/tests/mcp/test_tool_bm_read.py index c1bfdc3bf..df57e15e2 100644 --- a/tests/mcp/test_tool_bm_read.py +++ b/tests/mcp/test_tool_bm_read.py @@ -244,7 +244,9 @@ async def test_metadata_text_carries_the_qualified_path(client, test_project): await _write(test_project.name, "Plan", "# Plan") prefix = test_project.permalink - text = await read_text(f"{prefix}/notes/Plan.md", include_content=False) + text = await read_text( + f"{prefix}/notes/Plan.md", include_content=False, project=test_project.name + ) assert f"file_path: {prefix}/notes/Plan.md" in text diff --git a/tests/mcp/test_tool_bm_search.py b/tests/mcp/test_tool_bm_search.py index 677b60a7f..bd5bf2969 100644 --- a/tests/mcp/test_tool_bm_search.py +++ b/tests/mcp/test_tool_bm_search.py @@ -87,7 +87,12 @@ async def test_path_limits_the_search_to_a_folder(client, test_project): async def test_project_qualified_path_returns_qualified_paths(client, test_project): await _seed(test_project.name) - payload = await search_json(query="deploy", mode="text", path=f"{test_project.permalink}/tasks") + payload = await search_json( + query="deploy", + mode="text", + path=f"{test_project.permalink}/tasks", + project=test_project.name, + ) assert payload["results"][0]["file_path"] == f"{test_project.permalink}/tasks/Deploy Plan.md" @@ -359,7 +364,9 @@ async def test_a_project_qualified_memory_url_routes_the_search(client, test_pro """'memory:///...' searches the project it names, as a read would.""" await _seed(test_project.name) - payload = await search_json(query=f"memory://{test_project.permalink}/tasks/*") + payload = await search_json( + query=f"memory://{test_project.permalink}/tasks/*", project=test_project.name + ) assert [row["title"] for row in payload["results"]] == ["Deploy Plan"] @@ -382,7 +389,7 @@ async def test_results_across_projects_carry_routable_paths(client, test_project paths = [row["file_path"] for row in payload["results"]] assert f"{test_project.permalink}/tasks/Deploy Plan.md" in paths assert text.startswith("Results for 'rollback' in all projects:") - note = await bm_read(paths[0]) + note = await bm_read(paths[0], project=test_project.name) assert isinstance(note, str) diff --git a/tests/mcp/test_tool_bm_write.py b/tests/mcp/test_tool_bm_write.py index b528dc911..c0cc2f305 100644 --- a/tests/mcp/test_tool_bm_write.py +++ b/tests/mcp/test_tool_bm_write.py @@ -87,10 +87,14 @@ async def test_title_and_directory_derive_the_file_name(client, test_project): @pytest.mark.asyncio async def test_project_qualified_path_returns_a_qualified_path(client, test_project): - result = await write_json(identifier=f"{test_project.permalink}/plans/q4.md", content="Body") + result = await write_json( + identifier=f"{test_project.permalink}/plans/q4.md", + content="Body", + project=test_project.name, + ) assert result["file_path"] == f"{test_project.permalink}/plans/q4.md" - note = await bm_read(result["file_path"]) + note = await bm_read(result["file_path"], project=test_project.name) assert isinstance(note, str) and "Body" in note @@ -115,7 +119,9 @@ async def test_requested_path_is_qualified_like_the_request(client, test_project await bm_write(identifier="Plans/seed.md", content="Seed", project=test_project.name) prefix = test_project.permalink - result = await write_json(identifier=f"{prefix}/plans/q4.md", content="Body") + result = await write_json( + identifier=f"{prefix}/plans/q4.md", content="Body", project=test_project.name + ) assert result["file_path"] == f"{prefix}/Plans/q4.md" assert result["requested_file_path"] == f"{prefix}/plans/q4.md" @@ -266,7 +272,7 @@ async def lost(*_args: Any, **_kwargs: Any) -> None: NoteTargetMoved( external_id="abc", title="A", file_path="moved/a.md", permalink="moved/a" ), - r"^ALREADY_EXISTS: .*moved to 'moved/a.md'.*\nTry instead: bm_read\(identifier='moved/a.md'\)", + r"^ALREADY_EXISTS: .*moved to 'moved/a.md'.*\nTry instead: bm_read\(identifier='moved/a.md', project=", ), (NoteLocked(message="Note is locked for review."), "^LOCKED: Note is locked"), ], @@ -298,7 +304,7 @@ async def neighbors(*_args: Any, **_kwargs: Any) -> list[SimilarNote]: assert "## Similar existing notes" in text assert "bm_edit(identifier='notes/o.md'" in text - assert "bm_delete(identifier='notes/new.md')" in text + assert f"bm_delete(identifier='notes/new.md', project='{test_project.name}')" in text assert payload["similar_notes"][0]["title"] == "Old Plan" @@ -309,11 +315,15 @@ async def neighbors(*_args: Any, **_kwargs: Any) -> list[SimilarNote]: monkeypatch.setattr(write_module, "find_similar_notes", neighbors) prefix = test_project.permalink - text = await write_text(identifier=f"{prefix}/notes/new.md", content="Body") - payload = await write_json(identifier=f"{prefix}/notes/newer.md", content="Body") + text = await write_text( + identifier=f"{prefix}/notes/new.md", content="Body", project=test_project.name + ) + payload = await write_json( + identifier=f"{prefix}/notes/newer.md", content="Body", project=test_project.name + ) assert f"bm_edit(identifier='{prefix}/notes/o.md'" in text - assert f"bm_delete(identifier='{prefix}/notes/new.md')" in text + assert f"bm_delete(identifier='{prefix}/notes/new.md', project='{test_project.name}')" in text assert payload["similar_notes"][0]["file_path"] == f"{prefix}/notes/o.md" @@ -369,10 +379,15 @@ async def test_markdown_suffix_is_kept(client, test_project): @pytest.mark.asyncio async def test_existing_note_hint_names_the_qualified_path(client, test_project): prefix = test_project.permalink - await bm_write(identifier=f"{prefix}/notes/a.md", content="One") + await bm_write(identifier=f"{prefix}/notes/a.md", content="One", project=test_project.name) with pytest.raises(ToolError, match=f"bm_edit\\(identifier='{prefix}/notes/a.md'"): - await bm_write(identifier=f"{prefix}/notes/a.md", content="Two", overwrite=False) + await bm_write( + identifier=f"{prefix}/notes/a.md", + content="Two", + overwrite=False, + project=test_project.name, + ) @pytest.mark.asyncio diff --git a/tests/mcp/test_tool_params.py b/tests/mcp/test_tool_params.py index 2e8106614..33212229d 100644 --- a/tests/mcp/test_tool_params.py +++ b/tests/mcp/test_tool_params.py @@ -37,8 +37,8 @@ @probe_server.tool def probe( identifier: NoteIdentifier, + project: ProjectParam, path: DirectoryPath = "/", - project: ProjectParam = None, since: Since = "7d", page: Page = 1, page_size: PageSize = 10, @@ -59,6 +59,8 @@ def probe( async def call_probe(**arguments: Any) -> dict[str, Any]: + if "project_id" not in arguments: + arguments.setdefault("project", "research") async with Client(probe_server) as client: result = await client.call_tool("probe", arguments) assert result.structured_content is not None @@ -66,6 +68,7 @@ async def call_probe(**arguments: Any) -> dict[str, Any]: async def probe_error(**arguments: Any) -> str: + arguments.setdefault("project", "research") async with Client(probe_server) as client: result = await client.call_tool("probe", arguments, raise_on_error=False) assert result.is_error @@ -89,7 +92,7 @@ async def test_schema_lists_primary_names_only(): "filters", "items", } - assert tool.input_schema["required"] == ["identifier"] + assert tool.input_schema["required"] == ["identifier", "project"] # --- Hidden aliases --- From 194a8ff9fc81a82b571523aae17868c8f274619d Mon Sep 17 00:00:00 2001 From: phernandez Date: Wed, 28 Oct 2026 17:00:02 -0500 Subject: [PATCH 2/3] fix(mcp): propagate required scope through prompts and skills Signed-off-by: phernandez --- .../memory-capture/REFERENCE.md | 13 +++- .../memory-continue/REFERENCE.md | 52 +++++++++----- .../memory-notes/REFERENCE.md | 70 +++++++++++++------ .../memory-tasks/REFERENCE.md | 45 +++++++----- scripts/skill-bundle/basic-memory.md | 6 +- skills/README.md | 12 ++-- skills/memory-agents/SKILL.md | 23 ++++-- skills/memory-capture/SKILL.md | 13 +++- skills/memory-comark/SKILL.md | 13 +++- skills/memory-continue/SKILL.md | 52 +++++++++----- skills/memory-curate/SKILL.md | 32 ++++++--- skills/memory-defrag/SKILL.md | 17 ++++- skills/memory-ingest/SKILL.md | 38 +++++++--- skills/memory-lifecycle/SKILL.md | 27 +++++-- skills/memory-literary-analysis/SKILL.md | 67 ++++++++++++------ skills/memory-metadata-search/SKILL.md | 46 +++++++----- skills/memory-notes/SKILL.md | 70 +++++++++++++------ skills/memory-okf/SKILL.md | 28 +++++--- skills/memory-onboarding/SKILL.md | 17 ++++- .../references/schema-guide.md | 11 +-- skills/memory-quest/SKILL.md | 11 +++ skills/memory-reflect/SKILL.md | 26 +++++-- skills/memory-research/SKILL.md | 27 +++++-- skills/memory-schema/SKILL.md | 45 +++++++----- skills/memory-tasks/SKILL.md | 45 +++++++----- .../mcp/prompts/continue_conversation.py | 20 +++--- src/basic_memory/mcp/prompts/search.py | 13 ++-- tests/mcp/test_required_project.py | 41 +++++++++-- 28 files changed, 624 insertions(+), 256 deletions(-) diff --git a/integrations/pi/skill-references/memory-capture/REFERENCE.md b/integrations/pi/skill-references/memory-capture/REFERENCE.md index 3cf9e482c..6b1cac205 100644 --- a/integrations/pi/skill-references/memory-capture/REFERENCE.md +++ b/integrations/pi/skill-references/memory-capture/REFERENCE.md @@ -14,6 +14,17 @@ description: "Capture a working thread's current state into one coherent Basic M Capture the gist of a working thread — the decisions made, insights surfaced, and context built — into a single coherent Basic Memory note that reflects where the thread has landed. +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## Purpose A thread has a beginning, middle, and end. Things change as the conversation progresses: an early decision gets revised, a problem looks different in light of new information, a trade-off is settled differently than it first seemed. When this skill is invoked, capture the **current state of understanding**, not the history of how it got there. @@ -40,7 +51,7 @@ To rewrite the same note on re-capture instead of duplicating, key the note to a > **Example (hosts with a JSONL transcript):** some agents write a per-session transcript whose filename is a stable session UUID. If yours does, you can derive the id from the most-recently-modified transcript file and use it as `thread_id`. This is optional — only do it if your host actually exposes such a transcript. -**If no stable id is available**, match the existing note by title/topic instead: search for a note covering the same thread (`bm_search(query="")`), and if you find the one this thread already produced, rewrite it. Omit `thread_id` and rely on a consistent title. +**If no stable id is available**, match the existing note by title/topic instead: search for a note covering the same thread (`bm_search(query="", project="")`), and if you find the one this thread already produced, rewrite it. Omit `thread_id` and rely on a consistent title. ## Decision Flow diff --git a/integrations/pi/skill-references/memory-continue/REFERENCE.md b/integrations/pi/skill-references/memory-continue/REFERENCE.md index 07a932fc2..e20340db5 100644 --- a/integrations/pi/skill-references/memory-continue/REFERENCE.md +++ b/integrations/pi/skill-references/memory-continue/REFERENCE.md @@ -14,6 +14,17 @@ description: "Resume prior work by rebuilding context from the Basic Memory grap Resume previous work by reconstructing context from the Basic Memory knowledge graph, so the assistant can pick up across sessions instead of starting cold. +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## When to Use - Starting a new session and you need to pick up where you left off @@ -40,19 +51,20 @@ bm_context( identifier="memory://topic-or-note-name", depth=2, # how many relation hops to follow since="7d", # only include changes in this window + project="", ) ``` -**No clear starting point — use `bm_project(command="recent")`.** See what's changed and let it surface the thread: +**No clear starting point — use `bm_project(command="recent", project="")`.** See what's changed and let it surface the thread: ```python -bm_project(command="recent", since="3d") +bm_project(command="recent", since="3d", project="") ``` **Looking for something specific — use `bm_search`.** Find candidate notes by keyword: ```python -bm_search(query="async client refactor", page_size=10) +bm_search(query="async client refactor", page_size=10, project="") ``` ### 3. Read the Key Notes @@ -60,7 +72,7 @@ bm_search(query="async client refactor", page_size=10) Once you've identified the relevant notes, read them in full: ```python -bm_read(identifier="note-title-or-permalink") +bm_read(identifier="note-title-or-permalink", project="") ``` For long notes, pick before you pay for bodies. `compact=True` drops bodies from @@ -68,9 +80,9 @@ search results (and observations from `bm_context`), and a line range or a section reads only the part you need: ```python -bm_search(query="async client refactor", compact=True) -bm_read(identifier="note-title-or-permalink", start_line=120, end_line=180) -bm_read(identifier="note-title-or-permalink", section="Status") +bm_search(query="async client refactor", compact=True, project="") +bm_read(identifier="note-title-or-permalink", start_line=120, end_line=180, project="") +bm_read(identifier="note-title-or-permalink", section="Status", project="") ``` ### 4. Present Context to the User @@ -96,7 +108,7 @@ Use a specific note URL to anchor on one starting point; use a wildcard to pull ## Timeframe Reference -`bm_context` and `bm_project(command="recent")` accept natural-language timeframes: +`bm_context` and `bm_project(command="recent", project="")` accept natural-language timeframes: | Timeframe | Meaning | |-----------|---------| @@ -113,10 +125,10 @@ Use a specific note URL to anchor on one starting point; use a wildcard to pull ```python # 1. Read the spec / project note -bm_read(identifier="SPEC-24: Postgres Database Migration") +bm_read(identifier="SPEC-24: Postgres Database Migration", project="") # 2. Pull in related context and recent changes via the graph -bm_context(identifier="memory://SPEC-24*", since="7d") +bm_context(identifier="memory://SPEC-24*", since="7d", project="") ``` Then summarize: the goals, what's completed, what's pending, and any blockers or open decisions. @@ -125,10 +137,10 @@ Then summarize: the goals, what's completed, what's pending, and any blockers or ```python # 1. Check recent activity -bm_project(command="recent", since="3d") +bm_project(command="recent", since="3d", project="") # 2. Read notes from the recent sessions it surfaces -bm_read(identifier="relevant-note") +bm_read(identifier="relevant-note", project="") ``` Then list the modified notes with brief descriptions and ask which thread to dive into. @@ -137,10 +149,10 @@ Then list the modified notes with brief descriptions and ask which thread to div ```python # 1. Find the topic -bm_search(query="topic keywords") +bm_search(query="topic keywords", project="") # 2. Build context from the best match, following its relations -bm_context(identifier="memory://found-note-permalink", depth=2) +bm_context(identifier="memory://found-note-permalink", depth=2, project="") ``` Then present the full picture — the note plus its connected context. @@ -153,11 +165,19 @@ Project names are user-specific. To discover what's available before scoping a s bm_project(command="list") ``` -In multi-project setups, prefix a `memory://` URL with the project name (e.g. `memory://research/papers/crdt`) to scope it. +A qualified `memory://` URL (e.g. `memory://research/papers/crdt`) must agree +with `project`; the prefix does not replace that required parameter. + +For an explicitly broader search, use one of these scopes instead: + +```python +bm_search(query="topic keywords", projects=["research", "team/engineering"]) +bm_search(query="topic keywords", all_projects=True) +``` ## Guidelines -1. **Start broad, then narrow.** Get an overview with `bm_project(command="recent")` or a wildcard `bm_context`, then drill into specific notes. +1. **Start broad, then narrow.** Get an overview with `bm_project(command="recent", project="")` or a wildcard `bm_context`, then drill into specific notes. 2. **Present incrementally.** Share what you find as you go rather than holding everything until the end. 3. **Follow relations.** The graph's connections are the point — `bm_context` with `depth` surfaces context you wouldn't find by reading one note. 4. **Check multiple projects.** Specs may live separately from implementation notes; discover projects with `bm_project(command="list")`. diff --git a/integrations/pi/skill-references/memory-notes/REFERENCE.md b/integrations/pi/skill-references/memory-notes/REFERENCE.md index c82e833ce..94e1ba6a0 100644 --- a/integrations/pi/skill-references/memory-notes/REFERENCE.md +++ b/integrations/pi/skill-references/memory-notes/REFERENCE.md @@ -14,6 +14,17 @@ description: "How to write well-structured Basic Memory notes: frontmatter, cate Write well-structured notes that Basic Memory can parse into a searchable knowledge graph. Every note is a markdown file with three key sections: frontmatter, observations, and relations. +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## Note Anatomy ```markdown @@ -106,7 +117,7 @@ A few examples to illustrate the range: - **One fact per observation.** Don't pack multiple ideas into one line. - **Be specific.** `[decision] Use JWT` is less useful than `[decision] Use JWT with 15-minute expiry for API auth`. - **Use tags for cross-cutting concerns.** `[risk] Rate limiting needed #api #security` makes this findable under both topics. -- **Categories are queryable.** `bm_search(items=["observation"], categories=["decision"])` returns every decision observation across your knowledge base. +- **Categories are queryable.** `bm_search(items=["observation"], categories=["decision"], project="")` returns every decision observation across your knowledge base. ### When a Claim Holds @@ -135,8 +146,8 @@ An observation can say when it is true. Put a qualifier after the category: Search by what notes say was true, rather than by when they were edited: ```python -bm_search(valid_at="2026-07-01") # true on that date -bm_search(time_kind="due", valid_overlaps="[2026-10-14,2026-10-21)") # due this week +bm_search(valid_at="2026-07-01", project="") # true on that date +bm_search(time_kind="due", valid_overlaps="[2026-10-14,2026-10-21)", project="") # due this week ``` A valid-time filter returns only dated observations; drop it to search @@ -188,7 +199,7 @@ These create `references` relations automatically. Use the Relations section for - **Link liberally.** Relations are what turn isolated notes into a knowledge graph. When in doubt, add the link. - **Create target notes if they don't exist yet.** `[[Future Topic]]` is valid — BM will resolve it when that note is created. -- **Use `bm_context` to traverse.** `bm_context(identifier="memory://note-title")` follows relations to gather connected knowledge. +- **Use `bm_context` to traverse.** `bm_context(identifier="memory://note-title", project="")` follows relations to gather connected knowledge. - **Custom relation types are fine.** `taught_by`, `blocks`, `tested_in` — use whatever is descriptive. ## Memory URLs @@ -215,7 +226,10 @@ memory://main/specs/api-design # "main" project, "specs/api-design" path memory://research/papers/crdt # "research" project ``` -The first path segment is matched against known project names. If it matches, it's used as the project scope. Otherwise pass `project` explicitly when several projects are addressable; unqualified calls are refused. +Always pass `project` explicitly, even with a project-qualified URL or one +configured project. A recognized project prefix must agree with that parameter; +it does not replace it. Use a project external ID or `workspace/project` when +names collide across workspaces. ### Using Memory URLs @@ -223,13 +237,13 @@ Memory URLs work with `bm_context` to assemble related knowledge by traversing r ```python # Get a note and its connected context -bm_context(identifier="memory://api-design-decisions") +bm_context(identifier="memory://api-design-decisions", project="") # Wildcard — gather all docs -bm_context(identifier="memory://docs/*") +bm_context(identifier="memory://docs/*", project="") # Direct read by permalink -bm_read(identifier="memory://api-design-decisions") +bm_read(identifier="memory://api-design-decisions", project="") ``` ## Before Creating a Note @@ -242,9 +256,9 @@ A single search often misses. Try the full name, abbreviations, acronyms, and ke ```python # Searching for an entity that might already exist -bm_search(query="Kubernetes Migration") -bm_search(query="k8s migration") -bm_search(query="container migration") +bm_search(query="Kubernetes Migration", project="") +bm_search(query="k8s migration", project="") +bm_search(query="container migration", project="") ``` For people, try full name and last name. For organizations, try the full name and common abbreviations. @@ -265,7 +279,8 @@ bm_edit( identifier="API Design Decisions", command="insert_after_section", section="Observations", - content="- [decision] Switched to OpenAPI 3.1 for spec generation #api" + content="- [decision] Switched to OpenAPI 3.1 for spec generation #api", + project="", ) # Fix outdated information @@ -273,7 +288,8 @@ bm_edit( identifier="API Design Decisions", command="find_replace", find_text="- [status] draft", - content="- [status] approved" + content="- [status] approved", + project="", ) # Add a new relation @@ -281,7 +297,8 @@ bm_edit( identifier="API Design Decisions", command="insert_after_section", section="Relations", - content="- depends_on [[Rate Limiter]]" + content="- depends_on [[Rate Limiter]]", + project="", ) ``` @@ -310,7 +327,8 @@ flexibility matters more. ## Relations - implements [[API Specification]] -- relates_to [[Backend Architecture]]""" +- relates_to [[Backend Architecture]]""", + project="", ) ``` @@ -328,7 +346,8 @@ bm_edit( identifier="API Design Decisions", command="insert_after_section", section="Observations", - content="- [decision] Use OpenAPI 3.1 for spec generation #api" + content="- [decision] Use OpenAPI 3.1 for spec generation #api", + project="", ) # append / prepend — add to the end of the note or the start of the body @@ -336,7 +355,8 @@ bm_edit( bm_edit( identifier="API Design Decisions", command="prepend", - content="> Updated 2026-05-28: auth approach finalized.\n" + content="> Updated 2026-05-28: auth approach finalized.\n", + project="", ) # replace_section — rewrite a named section (use for living content that stays current) @@ -344,7 +364,8 @@ bm_edit( identifier="API Design Decisions", command="replace_section", section="Summary", - content="Concise, current summary of the decision and its rationale." + content="Concise, current summary of the decision and its rationale.", + project="", ) # find_replace — swap specific text @@ -352,7 +373,8 @@ bm_edit( identifier="API Design Decisions", command="find_replace", find_text="OpenAPI 3.0", - content="OpenAPI 3.1" + content="OpenAPI 3.1", + project="", ) ``` @@ -360,18 +382,19 @@ When an edit is destructive (`replace_section`, `find_replace`), read the note f and pass its checksum, so the edit applies only to the revision you read: ```python -note = bm_read(identifier="API Design Decisions", output_format="json") +note = bm_read(identifier="API Design Decisions", output_format="json", project="") bm_edit( identifier="API Design Decisions", command="replace_section", section="Summary", content="Concise, current summary of the decision and its rationale.", - expected_checksum=note["checksum"] + expected_checksum=note["checksum"], + project="", ) ``` A checksum conflict means someone changed the note after you read it. Read it -again and redo the edit against the new text. `bm_write(overwrite=True)` takes +again and redo the edit against the new text. `bm_write(overwrite=True, project="")` takes `expected_checksum` the same way. ### Moving a Note @@ -381,7 +404,8 @@ Use `bm_move` to reorganize notes into different directories: ```python bm_move( identifier="API Design Decisions", - destination="archive/api-design-decisions.md" + destination="archive/api-design-decisions.md", + project="", ) ``` diff --git a/integrations/pi/skill-references/memory-tasks/REFERENCE.md b/integrations/pi/skill-references/memory-tasks/REFERENCE.md index e538def4e..28b6a5209 100644 --- a/integrations/pi/skill-references/memory-tasks/REFERENCE.md +++ b/integrations/pi/skill-references/memory-tasks/REFERENCE.md @@ -14,6 +14,17 @@ description: "Task management via Basic Memory schemas: create, track, and resum Manage work-in-progress using Basic Memory's schema system. Tasks are just notes with `type: Task` — they live in the knowledge graph, validate against a schema, and survive context compaction. +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## When to Use - **Starting multi-step work** (3+ steps, or anything that might outlast the context window) @@ -82,18 +93,19 @@ What future-you needs to pick up this work. Include: - Key file paths and repos involved - Decisions already made and why - What was tried and what worked/didn't -- Where to look for related context""" +- Where to look for related context""", + project="", ) ``` -**Why both frontmatter and observations?** Fields in `metadata` (stored as frontmatter) power `bm_search` with `filters`. Fields as observations (`- [status] active`) power `bm_schema(command="validate")`. Include queryable fields in both places for full coverage. +**Why both frontmatter and observations?** Fields in `metadata` (stored as frontmatter) power `bm_search` with `filters`. Fields as observations (`- [status] active`) power `bm_schema(command="validate", project="")`. Include queryable fields in both places for full coverage. ### Key Principles - **Steps are concrete and checkable** — "Implement X in file Y", not "figure out stuff" - **Context is for post-amnesia resumption** — Write it as if explaining to a smart person who knows nothing about what you've been doing - **Relations link to other entities** — `parent_task [[Other Task]]`, `related_to [[Some Note]]` -- **Note types are normalized to snake_case** — `bm_write(note_type="Task")` stores `type: task`, and `note_types=["Task"]` or `note_types=["task"]` both match it. +- **Note types are normalized to snake_case** — `bm_write(note_type="Task", project="")` stores `type: task`, and `note_types=["Task"]` or `note_types=["task"]` both match it. ## Resuming After Compaction @@ -101,7 +113,7 @@ On session start or after compaction: 1. **Search for active tasks:** ```python - bm_search(note_types=["task"], filters={"status": "active"}) + bm_search(note_types=["task"], filters={"status": "active"}, project="") ``` 2. **Read the task note** to get full context @@ -131,12 +143,13 @@ writing. Update frontmatter too, with `command="set_metadata"` and the `metadata` parameter (the body stays unchanged): ```python -task = bm_read(identifier="tasks/descriptive-task-name", output_format="json") +task = bm_read(identifier="tasks/descriptive-task-name", output_format="json", project="") bm_edit( identifier="tasks/descriptive-task-name", command="set_metadata", metadata={"current_step": 3}, - expected_checksum=task["checksum"] + expected_checksum=task["checksum"], + project="", ) ``` @@ -154,7 +167,7 @@ Add a brief summary of what was accomplished and any follow-up needed. When a compaction event is imminent: -1. Find all active tasks: `bm_search(note_types=["task"], filters={"status": "active"})` +1. Find all active tasks: `bm_search(note_types=["task"], filters={"status": "active"}, project="")` 2. For each, update: - `current_step` to reflect actual progress - `context` with everything needed to resume @@ -167,14 +180,14 @@ With BM's schema system, tasks are fully queryable: | Query | What it finds | |-------|--------------| -| `bm_search(note_types=["task"])` | All tasks | -| `bm_search(note_types=["task"], filters={"status": "active"})` | Active tasks | -| `bm_search(note_types=["task"], filters={"status": "blocked"})` | Blocked tasks | -| `bm_search(note_types=["task"], filters={"assigned_to": "claude"})` | My tasks | -| `bm_search("blockers", note_types=["task"])` | Tasks with blockers | -| `bm_search(note_types=["task"], time_kind="due", valid_overlaps="[2026-10-14,2026-10-21)")` | Tasks with a step due this week | -| `bm_schema(command="validate", note_type="Task")` | Validate all tasks against schema | -| `bm_schema(command="diff", note_type="Task")` | Detect drift between schema and actual task notes | +| `bm_search(note_types=["task"], project="")` | All tasks | +| `bm_search(note_types=["task"], filters={"status": "active"}, project="")` | Active tasks | +| `bm_search(note_types=["task"], filters={"status": "blocked"}, project="")` | Blocked tasks | +| `bm_search(note_types=["task"], filters={"assigned_to": "claude"}, project="")` | My tasks | +| `bm_search("blockers", note_types=["task"], project="")` | Tasks with blockers | +| `bm_search(note_types=["task"], time_kind="due", valid_overlaps="[2026-10-14,2026-10-21)", project="")` | Tasks with a step due this week | +| `bm_schema(command="validate", note_type="Task", project="")` | Validate all tasks against schema | +| `bm_schema(command="diff", note_type="Task", project="")` | Detect drift between schema and actual task notes | ### Due Dates @@ -195,4 +208,4 @@ also returns overdue items. - **Context > steps** — Steps tell you what to do; context tells you why and how - **Close finished tasks** — Don't leave completed work as `active` - **Link related tasks** — Use `parent_task [[X]]` or relations to connect related work -- **Schema validation is your friend** — Run `bm_schema(command="validate", note_type="Task")` periodically to catch incomplete tasks +- **Schema validation is your friend** — Run `bm_schema(command="validate", note_type="Task", project="")` periodically to catch incomplete tasks diff --git a/scripts/skill-bundle/basic-memory.md b/scripts/skill-bundle/basic-memory.md index 10125c47e..fae88d5ec 100644 --- a/scripts/skill-bundle/basic-memory.md +++ b/scripts/skill-bundle/basic-memory.md @@ -22,7 +22,11 @@ conversation. What one session learns, the next one can find. user agrees, unless they have told you otherwise. - **Don't overwrite by accident.** Pass `overwrite: false` to `bm_write` unless you are deliberately replacing a note you have read in full. -- **Name the project.** Pass the project on every call. Ask when it is unclear. +- **Name the project.** Discover projects with `bm_project(command="list")` when + needed, then pass `project` on every note, folder, context and schema call and + on recent activity. A project name, `workspace/project`, or external ID works; + a qualified path does not replace it. Search requires `project`, `projects`, or + `all_projects=True`. Discovery and bundled manuals need no scope. ## Routing diff --git a/skills/README.md b/skills/README.md index 18c53094f..2b5ce1c00 100644 --- a/skills/README.md +++ b/skills/README.md @@ -19,17 +19,21 @@ These skills target the Basic Memory 1.0 MCP surface. Use `bm_man(page="bm_searc - `bm_write` creates or replaces a note; use its exact `identifier` path when replacing it. - `bm_edit` uses `command`, including `set_metadata` for frontmatter-only updates. - `bm_move` takes `destination`; `bm_delete` removes a note or directory. -- `bm_list` lists one folder level. At `/` without `project`, it lists projects. +- `bm_list` lists one folder level within its required project; `/` is that project's root. `bm_find` recurses and supports `filters` plus `fields` for metadata discovery. - `bm_search` takes `mode`, `filters`, `items`, and `since`; `lines` requests matching lines. - `bm_context` takes `identifier`, graph `depth`, and `since`. -- `bm_project(command="list"|"create"|"recent")` handles project discovery and activity. -- `bm_schema(command="validate"|"infer"|"diff")` handles schemas. +- `bm_project(command="list")` discovers projects without scope; `create` creates one. + `bm_project(command="recent", project="")` shows scoped activity. +- `bm_schema(command="validate"|"infer"|"diff", project="")` handles schemas. - Cloud adds `bm_agent` and Cloud-only read options. Check that the connected server exposes them before using those workflows. `project` accepts a name, `workspace/project`, or external ID. Pass it explicitly -when working across projects. Page list/find/search results until `has_more` is +on every note, folder, context and schema call, even with one project or a qualified +target. Recent activity also requires it. Search needs `project`, `projects`, or +`all_projects=True`; discovery and bundled manuals need no project. +Page list/find/search results until `has_more` is false (maximum `page_size=100`); context pages currently cap at 50. For revision-guarded changes, read as JSON and pass `checksum` as `expected_checksum`. The CLI examples retain their `bm cat`, `bm find`, and other CLI command shapes. diff --git a/skills/memory-agents/SKILL.md b/skills/memory-agents/SKILL.md index 2d73715fe..de6a40026 100644 --- a/skills/memory-agents/SKILL.md +++ b/skills/memory-agents/SKILL.md @@ -14,6 +14,17 @@ Agents run in Basic Memory Cloud only, on plans that include them. A local Basic Memory has no agent tools. Confirm the connected server exposes `bm_agent` before starting this workflow. +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## When to Use - The user wants recurring work on their notes done for them: follow up on @@ -25,11 +36,11 @@ before starting this workflow. | Tool | Does | |---|---| -| `bm_agent(command="list")` | The project's agents and how their recent runs went | -| `bm_agent(command="run")` | Starts an agent on a note; returns the run id | -| `bm_agent(command="get")` | One run: status, notes changed, and the agent's last reply | -| `bm_agent(command="runs")` | Recent runs, newest first, optionally for one agent | -| `bm_agent(command="mark")` | Mark a run `kept` or `dismissed` with `run_id` and `decision` | +| `bm_agent(command="list", project="")` | The project's agents and how their recent runs went | +| `bm_agent(command="run", project="")` | Starts an agent on a note; returns the run id | +| `bm_agent(command="get", project="")` | One run: status, notes changed, and the agent's last reply | +| `bm_agent(command="runs", project="")` | Recent runs, newest first, optionally for one agent | +| `bm_agent(command="mark", project="")` | Mark a run `kept` or `dismissed` with `run_id` and `decision` | Create and edit agents with `bm_write` and `bm_edit`. There is no separate agent tool for that. @@ -130,7 +141,7 @@ on the version the person ended with. Notes written by agents, imports, or ## Check a Run -`bm_agent(command="get")` shows the status, the notes the run created, edited, moved, or +`bm_agent(command="get", project="")` shows the status, the notes the run created, edited, moved, or deleted, and the agent's last reply. Every reply is also kept in a run log note, `agents/runs/ run `. Read it for the whole conversation; do not edit it. diff --git a/skills/memory-capture/SKILL.md b/skills/memory-capture/SKILL.md index 16abb480e..e9de18a25 100644 --- a/skills/memory-capture/SKILL.md +++ b/skills/memory-capture/SKILL.md @@ -7,6 +7,17 @@ description: "Capture a working thread's current state into one coherent Basic M Capture the gist of a working thread — the decisions made, insights surfaced, and context built — into a single coherent Basic Memory note that reflects where the thread has landed. +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## Purpose A thread has a beginning, middle, and end. Things change as the conversation progresses: an early decision gets revised, a problem looks different in light of new information, a trade-off is settled differently than it first seemed. When this skill is invoked, capture the **current state of understanding**, not the history of how it got there. @@ -33,7 +44,7 @@ To rewrite the same note on re-capture instead of duplicating, key the note to a > **Example (hosts with a JSONL transcript):** some agents write a per-session transcript whose filename is a stable session UUID. If yours does, you can derive the id from the most-recently-modified transcript file and use it as `thread_id`. This is optional — only do it if your host actually exposes such a transcript. -**If no stable id is available**, match the existing note by title/topic instead: search for a note covering the same thread (`bm_search(query="")`), and if you find the one this thread already produced, rewrite it. Omit `thread_id` and rely on a consistent title. +**If no stable id is available**, match the existing note by title/topic instead: search for a note covering the same thread (`bm_search(query="", project="")`), and if you find the one this thread already produced, rewrite it. Omit `thread_id` and rely on a consistent title. ## Decision Flow diff --git a/skills/memory-comark/SKILL.md b/skills/memory-comark/SKILL.md index cc000bba2..1ae3a7859 100644 --- a/skills/memory-comark/SKILL.md +++ b/skills/memory-comark/SKILL.md @@ -19,6 +19,17 @@ The full vocabulary, every prop, and every data grammar are in [references/components.md](references/components.md). Read it before using a component you have not used before. +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## Pick a component Most notes need only these. The reference has the rest (39 in total). @@ -138,7 +149,7 @@ Semantics to state honestly in the surrounding prose: ### Check the rendered result before you quote it -In Basic Memory Cloud, `bm_read(view="text")` returns the note as a reader +In Basic Memory Cloud, `bm_read(identifier="", view="text", project="")` returns the note as a reader sees it: every component as plain Markdown, with live queries run now. Read it back after writing a live view and confirm the view has rows before you state a number in prose. A query over a field no note has renders an empty view. diff --git a/skills/memory-continue/SKILL.md b/skills/memory-continue/SKILL.md index d6f517745..a7a4c7973 100644 --- a/skills/memory-continue/SKILL.md +++ b/skills/memory-continue/SKILL.md @@ -7,6 +7,17 @@ description: "Resume prior work by rebuilding context from the Basic Memory grap Resume previous work by reconstructing context from the Basic Memory knowledge graph, so the assistant can pick up across sessions instead of starting cold. +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## When to Use - Starting a new session and you need to pick up where you left off @@ -33,19 +44,20 @@ bm_context( identifier="memory://topic-or-note-name", depth=2, # how many relation hops to follow since="7d", # only include changes in this window + project="", ) ``` -**No clear starting point — use `bm_project(command="recent")`.** See what's changed and let it surface the thread: +**No clear starting point — use `bm_project(command="recent", project="")`.** See what's changed and let it surface the thread: ```python -bm_project(command="recent", since="3d") +bm_project(command="recent", since="3d", project="") ``` **Looking for something specific — use `bm_search`.** Find candidate notes by keyword: ```python -bm_search(query="async client refactor", page_size=10) +bm_search(query="async client refactor", page_size=10, project="") ``` ### 3. Read the Key Notes @@ -53,7 +65,7 @@ bm_search(query="async client refactor", page_size=10) Once you've identified the relevant notes, read them in full: ```python -bm_read(identifier="note-title-or-permalink") +bm_read(identifier="note-title-or-permalink", project="") ``` For long notes, pick before you pay for bodies. `compact=True` drops bodies from @@ -61,9 +73,9 @@ search results (and observations from `bm_context`), and a line range or a section reads only the part you need: ```python -bm_search(query="async client refactor", compact=True) -bm_read(identifier="note-title-or-permalink", start_line=120, end_line=180) -bm_read(identifier="note-title-or-permalink", section="Status") +bm_search(query="async client refactor", compact=True, project="") +bm_read(identifier="note-title-or-permalink", start_line=120, end_line=180, project="") +bm_read(identifier="note-title-or-permalink", section="Status", project="") ``` ### 4. Present Context to the User @@ -89,7 +101,7 @@ Use a specific note URL to anchor on one starting point; use a wildcard to pull ## Timeframe Reference -`bm_context` and `bm_project(command="recent")` accept natural-language timeframes: +`bm_context` and `bm_project(command="recent", project="")` accept natural-language timeframes: | Timeframe | Meaning | |-----------|---------| @@ -106,10 +118,10 @@ Use a specific note URL to anchor on one starting point; use a wildcard to pull ```python # 1. Read the spec / project note -bm_read(identifier="SPEC-24: Postgres Database Migration") +bm_read(identifier="SPEC-24: Postgres Database Migration", project="") # 2. Pull in related context and recent changes via the graph -bm_context(identifier="memory://SPEC-24*", since="7d") +bm_context(identifier="memory://SPEC-24*", since="7d", project="") ``` Then summarize: the goals, what's completed, what's pending, and any blockers or open decisions. @@ -118,10 +130,10 @@ Then summarize: the goals, what's completed, what's pending, and any blockers or ```python # 1. Check recent activity -bm_project(command="recent", since="3d") +bm_project(command="recent", since="3d", project="") # 2. Read notes from the recent sessions it surfaces -bm_read(identifier="relevant-note") +bm_read(identifier="relevant-note", project="") ``` Then list the modified notes with brief descriptions and ask which thread to dive into. @@ -130,10 +142,10 @@ Then list the modified notes with brief descriptions and ask which thread to div ```python # 1. Find the topic -bm_search(query="topic keywords") +bm_search(query="topic keywords", project="") # 2. Build context from the best match, following its relations -bm_context(identifier="memory://found-note-permalink", depth=2) +bm_context(identifier="memory://found-note-permalink", depth=2, project="") ``` Then present the full picture — the note plus its connected context. @@ -146,11 +158,19 @@ Project names are user-specific. To discover what's available before scoping a s bm_project(command="list") ``` -In multi-project setups, prefix a `memory://` URL with the project name (e.g. `memory://research/papers/crdt`) to scope it. +A qualified `memory://` URL (e.g. `memory://research/papers/crdt`) must agree +with `project`; the prefix does not replace that required parameter. + +For an explicitly broader search, use one of these scopes instead: + +```python +bm_search(query="topic keywords", projects=["research", "team/engineering"]) +bm_search(query="topic keywords", all_projects=True) +``` ## Guidelines -1. **Start broad, then narrow.** Get an overview with `bm_project(command="recent")` or a wildcard `bm_context`, then drill into specific notes. +1. **Start broad, then narrow.** Get an overview with `bm_project(command="recent", project="")` or a wildcard `bm_context`, then drill into specific notes. 2. **Present incrementally.** Share what you find as you go rather than holding everything until the end. 3. **Follow relations.** The graph's connections are the point — `bm_context` with `depth` surfaces context you wouldn't find by reading one note. 4. **Check multiple projects.** Specs may live separately from implementation notes; discover projects with `bm_project(command="list")`. diff --git a/skills/memory-curate/SKILL.md b/skills/memory-curate/SKILL.md index 217939262..79cb23af5 100644 --- a/skills/memory-curate/SKILL.md +++ b/skills/memory-curate/SKILL.md @@ -9,6 +9,17 @@ Maintain a healthy, well-connected knowledge graph. As notes accumulate, it pays This skill curates the **knowledge graph** — the notes, relations, and tags that make up the knowledge base. (For the notes' content — splitting bloated notes, consolidating scattered facts, retiring stale entries — see **memory-defrag**.) +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## When to Use - Asked to organize, clean up, or improve the knowledge base @@ -26,8 +37,8 @@ Orphans have no relations to other notes — they're islands in the graph. ```python # List notes, then read each to inspect its Relations section -bm_search(query="*", mode="text", page_size=50) -bm_read(identifier="note-to-check") +bm_search(query="*", mode="text", page_size=50, project="") +bm_read(identifier="note-to-check", project="") # Orphans have an empty (or missing) Relations section ``` @@ -47,9 +58,9 @@ If the `bm` CLI is available, `bm orphans` lists notes with no relations in one Analyze a note's content and propose meaningful connections. ```python -bm_read(identifier="note-to-analyze") +bm_read(identifier="note-to-analyze", project="") # Pull out key terms, then search for related notes -bm_search(query="key terms from the note") +bm_search(query="key terms from the note", project="") ``` Suggest relations based on shared topics, complementary content (problem/solution, @@ -75,6 +86,7 @@ bm_edit( command="insert_after_section", section="Relations", content="- depends_on [[Rate Limiter]]", + project="", ) ``` @@ -86,6 +98,7 @@ bm_edit( identifier="API Design Decisions", command="append", content="\n## Relations\n- depends_on [[Rate Limiter]]", + project="", ) ``` @@ -94,7 +107,7 @@ bm_edit( Find notes that may cover the same ground. ```python -bm_search(query="topic keywords") +bm_search(query="topic keywords", project="") # Compare results for: similar titles, overlapping observations, # shared tags, close-together timestamps ``` @@ -112,6 +125,7 @@ bm_edit( command="insert_after_section", section="Relations", content="- updates [[DB Schema v2]]", + project="", ) ``` @@ -130,13 +144,14 @@ notes with `bm_move`. By default the permalink stays the same after a move, so l bm_move( identifier="API Design Decisions", destination="architecture/api-design-decisions.md", + project="", ) ``` ### 5. Tag Consistency ```python -bm_search(query="*", mode="text", page_size=100) +bm_search(query="*", mode="text", page_size=100, project="") # Inspect tag patterns across results ``` @@ -174,6 +189,7 @@ A hub linking architecture-related decisions and patterns. ## Relations - indexes [[Architecture]]""", + project="", ) ``` @@ -182,7 +198,7 @@ A hub linking architecture-related decisions and patterns. Find notes lacking structure and fill them in. ```python -bm_read(identifier="sparse-note") +bm_read(identifier="sparse-note", project="") ``` If the note is missing an Observations section, suggest categories. If it has no @@ -192,7 +208,7 @@ context, suggest adding background. Apply with `bm_edit`. ## Curation Workflows Scale the pass to the request. A health check reports orphans, likely duplicates, -recent activity (`bm_project(command="recent")`), and folder distribution. A deep session works +recent activity (`bm_project(command="recent", project="")`), and folder distribution. A deep session works through the capabilities above in whatever order the findings suggest. A topic pass maps one subject with `bm_search` and `bm_context`, fills the gaps it finds, and ends with a hub note. diff --git a/skills/memory-defrag/SKILL.md b/skills/memory-defrag/SKILL.md index cae1a687a..9d6fd2eac 100644 --- a/skills/memory-defrag/SKILL.md +++ b/skills/memory-defrag/SKILL.md @@ -10,6 +10,17 @@ time notes grow past their topic, the same fact lands in several places, old facts contradict new ones, and finished work lingers. Defrag fixes the content; **memory-curate** handles links, relations, and tags. +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## When to Run - **Periodic**: weekly or every other week @@ -30,13 +41,13 @@ notes nobody touched lately. bm_find(path="/", depth=10, page_size=100, project="") # Recently busy notes, to look at first -bm_project(command="recent", since="30d", output_format="json", page_size=50) +bm_project(command="recent", since="30d", output_format="json", page_size=50, project="") # Notes on one topic, to spot overlap -bm_search(query="launch plan") +bm_search(query="launch plan", project="") # Commitments due on or before today: finished work that lingers, or overdue items -bm_search(time_kind="due", valid_overlaps="(,2026-10-14]") +bm_search(time_kind="due", valid_overlaps="(,2026-10-14]", project="") ``` Read every note you might change, in full. For each, note its topic, size, last diff --git a/skills/memory-ingest/SKILL.md b/skills/memory-ingest/SKILL.md index 4aad14a67..3b6401c65 100644 --- a/skills/memory-ingest/SKILL.md +++ b/skills/memory-ingest/SKILL.md @@ -7,6 +7,17 @@ description: "Turn meeting transcripts, conversation logs, or pasted documents i Turn raw, unstructured input into structured Basic Memory entities. Meeting transcripts, conversation logs, pasted documents, email threads — anything with information worth preserving gets parsed, cross-referenced against existing knowledge, and written as proper notes. +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## When to Use - User pastes a meeting transcript or conversation log @@ -70,16 +81,16 @@ For each extracted entity, search Basic Memory with multiple query variations: ```python # Person — try full name, last name -bm_search(query="Sarah Chen") -bm_search(query="Chen") +bm_search(query="Sarah Chen", project="") +bm_search(query="Chen", project="") # Organization — try full name, abbreviation, acronym -bm_search(query="National Renewable Energy Laboratory") -bm_search(query="NREL") +bm_search(query="National Renewable Energy Laboratory", project="") +bm_search(query="NREL", project="") # Topic — try the full term and keywords -bm_search(query="edge computing") -bm_search(query="edge inference") +bm_search(query="edge computing", project="") +bm_search(query="edge inference", project="") ``` Classify each entity as: @@ -150,7 +161,8 @@ Brief one-sentence summary of what this meeting was about. - with [[NovaTech]] - discussed [[Federated Learning]] - follow_up [[Send NovaTech Technical Spec]] -""" +""", + project="", ) ``` @@ -177,7 +189,8 @@ bm_write( ## Relations - relates_to [[Edge Computing]] - relates_to [[Model Optimization]] -""" +""", + project="", ) ``` @@ -232,7 +245,8 @@ VP of Engineering at NovaTech. Met during integration partnership discussion. ## Relations - works_at [[NovaTech]] - discussed_in [[NovaTech Meeting - Jordan Rivera - Feb 22, 2026]] -""" +""", + project="", ) ``` @@ -262,7 +276,8 @@ SaaS platform company. Series B stage. ## Relations - employs [[Jordan Rivera]] - discussed_in [[NovaTech Meeting - Jordan Rivera - Feb 22, 2026]] -""" +""", + project="", ) ``` @@ -286,7 +301,8 @@ bm_write( ## Relations - discussed_in [[NovaTech Meeting - Jordan Rivera - Feb 22, 2026]] -""" +""", + project="", ) ``` diff --git a/skills/memory-lifecycle/SKILL.md b/skills/memory-lifecycle/SKILL.md index 9bd4c2906..8cdf380ff 100644 --- a/skills/memory-lifecycle/SKILL.md +++ b/skills/memory-lifecycle/SKILL.md @@ -7,6 +7,17 @@ description: "Manage note status transitions in Basic Memory: archive completed Manage how entities move through status stages in Basic Memory. The core principle: **archive, never delete.** Completed work is valuable context — move it out of the active view, but keep it in the knowledge graph. +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## When to Use - User says something is "done", "finished", "completed", "submitted", "missed", or "cancelled" @@ -77,8 +88,8 @@ When the user mentions completion or status change, extract the intent: Search Basic Memory with multiple variations to locate the entity: ```python -bm_search(query="quarterly report") -bm_search(query="Q1 report") +bm_search(query="quarterly report", project="") +bm_search(query="Q1 report", project="") ``` If multiple matches come back, present options and ask which one. @@ -92,7 +103,8 @@ Use `bm_move` to relocate the entity to the appropriate status folder: ```python bm_move( identifier="tasks/active/quarterly-report", - destination="tasks/completed/quarterly-report.md" + destination="tasks/completed/quarterly-report.md", + project="", ) ``` @@ -108,7 +120,8 @@ the body unchanged: bm_edit( identifier="tasks/completed/quarterly-report.md", command="set_metadata", - metadata={"status": "completed", "completed": "2026-02-22"} + metadata={"status": "completed", "completed": "2026-02-22"}, + project="", ) ``` @@ -150,13 +163,15 @@ If something was archived by mistake, move it back: ```python bm_move( identifier="tasks/completed/quarterly-report", - destination="tasks/active/quarterly-report.md" + destination="tasks/active/quarterly-report.md", + project="", ) bm_edit( identifier="tasks/active/quarterly-report.md", command="set_metadata", - metadata={"status": "active"} + metadata={"status": "active"}, + project="", ) ``` diff --git a/skills/memory-literary-analysis/SKILL.md b/skills/memory-literary-analysis/SKILL.md index 409444033..553d354fe 100644 --- a/skills/memory-literary-analysis/SKILL.md +++ b/skills/memory-literary-analysis/SKILL.md @@ -7,6 +7,17 @@ description: "Analyze a complete literary work into a structured Basic Memory kn Transform a complete literary work into a structured knowledge graph. Characters, themes, chapters, locations, symbols, and literary devices become interconnected notes — searchable, validatable, and traversable. +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## When to Use - Analyzing a novel, play, poem, or non-fiction book end-to-end @@ -63,10 +74,10 @@ audited: `/characters` reaches everything filed under `characters/` (including `characters/major/`), and never `characters-cut/`. -For MCP, use `bm_read(identifier="", section="Observations")` or -`start_line`/`end_line` for slices, `bm_find(filters={"type": "chapter"}, -fields=["chapter_number", "pov"])` for metadata, and `bm_search(query="doubloon", -lines=2)` for matching lines. `bm_list` lists one folder level; `bm_find` recurses. +For MCP, use `bm_read(identifier="", section="Observations", project="")` or +`start_line`/`end_line` for slices. Use `bm_find(filters={"type": "chapter"}, fields=["chapter_number", "pov"], project="")` +for metadata and `bm_search(query="doubloon", lines=2, project="")` +for matching lines. `bm_list` lists one folder level; `bm_find` recurses. MCP list/find/search pages cap at 100; follow `has_more` through every page. CLI page sizes and flags below are separate from the MCP shapes. @@ -109,7 +120,8 @@ Schema for character entity notes. ## Observations - [convention] Major characters in characters/major/, minor in characters/minor/ - [convention] Observation categories: trait, motivation, arc, quote, appearance, relationship, symbolism, fate -- [convention] Relations: appears_in, contrasts_with, allied_with, commands, symbolizes, associated_with""" +- [convention] Relations: appears_in, contrasts_with, allied_with, commands, symbolizes, associated_with""", + project="", ) ``` @@ -138,7 +150,8 @@ Schema for thematic analysis notes. ## Observations - [convention] Observation categories: definition, manifestation, evolution, counterpoint, quote, interpretation -- [convention] Relations: embodied_by, contrasts_with, reinforced_by, explored_in, expressed_through""" +- [convention] Relations: embodied_by, contrasts_with, reinforced_by, explored_in, expressed_through""", + project="", ) ``` @@ -167,7 +180,8 @@ Schema for chapter-level analysis notes. ## Observations - [convention] Chapters stored in chapters/ directory - [convention] Observation categories: summary, event, tone, technique, quote, significance, foreshadowing -- [convention] Relations: features, set_in, explores, contains, employs, follows, precedes, parallels""" +- [convention] Relations: features, set_in, explores, contains, employs, follows, precedes, parallels""", + project="", ) ``` @@ -194,7 +208,8 @@ Schema for location and setting notes. ## Observations - [convention] Observation categories: description, atmosphere, symbolism, significance, geography -- [convention] Relations: setting_for, associated_with, symbolizes, contains, part_of""" +- [convention] Relations: setting_for, associated_with, symbolizes, contains, part_of""", + project="", ) ``` @@ -221,7 +236,8 @@ Schema for symbolic element notes. ## Observations - [convention] Observation categories: meaning, appearance, ambiguity, interpretation, quote, evolution -- [convention] Relations: represents, associated_with, appears_in, contrasts_with, located_at""" +- [convention] Relations: represents, associated_with, appears_in, contrasts_with, located_at""", + project="", ) ``` @@ -248,7 +264,8 @@ Schema for literary technique and device notes. ## Observations - [convention] Observation categories: definition, usage, effect, example, significance -- [convention] Relations: used_in, characterizes, expresses, related_to""" +- [convention] Relations: used_in, characterizes, expresses, related_to""", + project="", ) ``` @@ -293,7 +310,8 @@ bm_write( ## Relations - associated_with [[]] -- appears_in [[]]""" +- appears_in [[]]""", + project="", ) ``` @@ -410,7 +428,8 @@ bm_write( - contains [[]] - employs [[]] - follows [[Chapter - ]] -- precedes [[Chapter - ]]""" +- precedes [[Chapter - ]]""", + project="", ) ``` @@ -422,7 +441,8 @@ bm_edit( command="insert_after_section", section="Observations", content="""- [arc] Ch.: -- [quote] "" (Ch.)""" +- [quote] "" (Ch.)""", + project="", ) ``` @@ -455,7 +475,7 @@ As each chapter is processed, append observations to relevant entities: ### Adding Prose and Interpretation -After the structured observations are in place, consider adding interpretive prose to major entity notes. Insert 2-4 paragraphs of critical essay before the Observations section with `bm_edit(command="insert_before_section", section="Observations", content=...)`. This prose should: +After the structured observations are in place, consider adding interpretive prose to major entity notes. Insert 2-4 paragraphs of critical essay before the Observations section with `bm_edit(command="insert_before_section", section="Observations", content=..., project="")`. This prose should: - Argue for a reading of the character, theme, or symbol — not just describe it - Connect the entity to the work's larger concerns and to literary tradition @@ -518,7 +538,8 @@ Analysis of the work's narrative architecture. - analyzes [[]] - analyzes [[]] - explores [[]] -...""" +...""", + project="", ) ``` @@ -536,18 +557,18 @@ During chapter processing, new minor characters, locations, and symbols will eme ```python # Validate each entity type -bm_schema(command="validate", note_type="Character") -bm_schema(command="validate", note_type="Theme") -bm_schema(command="validate", note_type="Chapter") -bm_schema(command="validate", note_type="Location") -bm_schema(command="validate", note_type="Symbol") -bm_schema(command="validate", note_type="LiteraryDevice") +bm_schema(command="validate", note_type="Character", project="") +bm_schema(command="validate", note_type="Theme", project="") +bm_schema(command="validate", note_type="Chapter", project="") +bm_schema(command="validate", note_type="Location", project="") +bm_schema(command="validate", note_type="Symbol", project="") +bm_schema(command="validate", note_type="LiteraryDevice", project="") ``` ### Drift Detection ```python -bm_schema(command="diff", note_type="Character") +bm_schema(command="diff", note_type="Character", project="") # ... for each type ``` @@ -741,7 +762,7 @@ This pipeline works for any literary text. Adjust schemas for genre: - **Relations are your web.** Every chapter should link to characters, themes, locations, and devices. Every entity should link back to chapters where it appears. - **Enrich iteratively.** Entity notes grow richer with each chapter. Don't try to write the perfect character note upfront — append as you go. - **Add prose for depth.** After structured data is in place, add interpretive essays to major notes. The prose captures what observations cannot: argument, nuance, opinion, and voice. -- **Validate periodically.** Run `bm_schema(command="validate")` after each batch, not just at the end. Catch drift early. +- **Validate periodically.** Run `bm_schema(command="validate", project="")` after each batch, not just at the end. Catch drift early. - **Quote generously.** Literary analysis lives on textual evidence. Include significant quotes as `[quote]` observations with chapter attribution. - **Review and revise.** After completing all chapters, review the full graph from an external perspective. Look for thin notes, missing connections, and gaps in coverage. The first pass is never the last. - **Analysis comes last.** Synthesis notes in `analysis/` should be written after all chapters are processed, when you have the full picture. diff --git a/skills/memory-metadata-search/SKILL.md b/skills/memory-metadata-search/SKILL.md index 61d052aac..cb1386144 100644 --- a/skills/memory-metadata-search/SKILL.md +++ b/skills/memory-metadata-search/SKILL.md @@ -7,6 +7,17 @@ description: "Search Basic Memory notes by custom frontmatter fields with equali Find notes by their structured frontmatter fields instead of (or in addition to) free-text content. Any custom YAML key in a note's frontmatter beyond the standard set (`title`, `type`, `tags`, `permalink`, `schema`) is automatically indexed as `entity_metadata` and becomes queryable. +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## When to Use - **Filtering by status or priority** — find all notes with `status: draft` or `priority: high` @@ -104,8 +115,8 @@ against the value and a comparison with null is never true. Frontmatter fields say when a note was filed or reviewed. To ask what a note *claims was true* on a date, use observation qualifiers (see **memory-notes**) -and `bm_search(valid_at="2026-07-01")` or -`bm_search(valid_overlaps="[2026-07-01,2026-08-01)")`. +and `bm_search(valid_at="2026-07-01", project="")` or +`bm_search(valid_overlaps="[2026-07-01,2026-08-01)", project="")`. ## Using `bm_search` with Metadata @@ -113,7 +124,7 @@ Pass `filters` to `bm_search`. Omit `query` for filter-only searches, or combine ```python # Filter-only — find all notes with a given status -bm_search(filters={"status": "in-progress"}) +bm_search(filters={"status": "in-progress"}, project="") # Filter-only — high-priority specs in a specific project bm_search( @@ -123,19 +134,20 @@ bm_search( ) # Filter-only — notes with confidence above a threshold -bm_search(filters={"confidence": {"$gt": 0.7}}) +bm_search(filters={"confidence": {"$gt": 0.7}}, project="") # Tags and status use the same filter syntax -bm_search(filters={"status": "active"}) -bm_search(filters={"tags": ["security", "oauth"]}) +bm_search(filters={"status": "active"}, project="") +bm_search(filters={"tags": ["security", "oauth"]}, project="") # Text search narrowed by metadata -bm_search("authentication", filters={"status": "draft"}) +bm_search("authentication", filters={"status": "draft"}, project="") # Mix text, tags, and an advanced filter bm_search( "oauth flow", filters={"tags": ["security"], "confidence": {"$gt": 0.7}}, + project="", ) ``` @@ -147,11 +159,11 @@ The `tag:` prefix in a query converts to a tag filter automatically: ```python # These are equivalent: -bm_search("tag:tier1") -bm_search(filters={"tags": ["tier1"]}) +bm_search("tag:tier1", project="") +bm_search(filters={"tags": ["tier1"]}, project="") # Multiple tags (comma or space separated) — all must match: -bm_search("tag:tier1,alpha") +bm_search("tag:tier1,alpha", project="") ``` ## Example: Custom Frontmatter in Practice @@ -182,19 +194,19 @@ Queries that find it: ```python # By status and type -bm_search(filters={"status": "in-progress", "type": "spec"}) +bm_search(filters={"status": "in-progress", "type": "spec"}, project="") # By numeric threshold -bm_search(filters={"confidence": {"$gt": 0.7}}) +bm_search(filters={"confidence": {"$gt": 0.7}}, project="") # By priority set -bm_search(filters={"priority": {"$in": ["high", "critical"]}}) +bm_search(filters={"priority": {"$in": ["high", "critical"]}}, project="") # By tag shorthand -bm_search("tag:security") +bm_search("tag:security", project="") # Combined text + metadata -bm_search("OAuth", filters={"status": "in-progress"}) +bm_search("OAuth", filters={"status": "in-progress"}, project="") ``` ## Guidelines @@ -203,6 +215,6 @@ bm_search("OAuth", filters={"status": "in-progress"}) - **Use text search for content queries.** If you're looking for notes *about* something, text search is better. Combine both when you need precision. - **Custom fields are free.** Any YAML key you put in frontmatter becomes queryable — no schema or configuration required. - **Multiple filters are AND.** `{"status": "active", "priority": "high"}` requires both conditions. -- **Omit `query` for filter-only searches.** `bm_search(filters={"status": "active"})` works without a text query. +- **Omit `query` for filter-only searches.** `bm_search(filters={"status": "active"}, project="")` works without a text query. - **Dot notation for nesting.** Access nested YAML structures with dots: `{"schema.version": "2"}` queries the `version` key inside a `schema` object. -- **Use the same filters for file discovery.** `bm_find(filters={"status": "active"}, fields=["title", "priority"])` returns selected frontmatter values without reading each note. +- **Use the same filters for file discovery.** `bm_find(filters={"status": "active"}, fields=["title", "priority"], project="")` returns selected frontmatter values without reading each note. diff --git a/skills/memory-notes/SKILL.md b/skills/memory-notes/SKILL.md index 1e9d4eeec..51c46cd77 100644 --- a/skills/memory-notes/SKILL.md +++ b/skills/memory-notes/SKILL.md @@ -7,6 +7,17 @@ description: "How to write well-structured Basic Memory notes: frontmatter, cate Write well-structured notes that Basic Memory can parse into a searchable knowledge graph. Every note is a markdown file with three key sections: frontmatter, observations, and relations. +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## Note Anatomy ```markdown @@ -99,7 +110,7 @@ A few examples to illustrate the range: - **One fact per observation.** Don't pack multiple ideas into one line. - **Be specific.** `[decision] Use JWT` is less useful than `[decision] Use JWT with 15-minute expiry for API auth`. - **Use tags for cross-cutting concerns.** `[risk] Rate limiting needed #api #security` makes this findable under both topics. -- **Categories are queryable.** `bm_search(items=["observation"], categories=["decision"])` returns every decision observation across your knowledge base. +- **Categories are queryable.** `bm_search(items=["observation"], categories=["decision"], project="")` returns every decision observation across your knowledge base. ### When a Claim Holds @@ -128,8 +139,8 @@ An observation can say when it is true. Put a qualifier after the category: Search by what notes say was true, rather than by when they were edited: ```python -bm_search(valid_at="2026-07-01") # true on that date -bm_search(time_kind="due", valid_overlaps="[2026-10-14,2026-10-21)") # due this week +bm_search(valid_at="2026-07-01", project="") # true on that date +bm_search(time_kind="due", valid_overlaps="[2026-10-14,2026-10-21)", project="") # due this week ``` A valid-time filter returns only dated observations; drop it to search @@ -181,7 +192,7 @@ These create `references` relations automatically. Use the Relations section for - **Link liberally.** Relations are what turn isolated notes into a knowledge graph. When in doubt, add the link. - **Create target notes if they don't exist yet.** `[[Future Topic]]` is valid — BM will resolve it when that note is created. -- **Use `bm_context` to traverse.** `bm_context(identifier="memory://note-title")` follows relations to gather connected knowledge. +- **Use `bm_context` to traverse.** `bm_context(identifier="memory://note-title", project="")` follows relations to gather connected knowledge. - **Custom relation types are fine.** `taught_by`, `blocks`, `tested_in` — use whatever is descriptive. ## Memory URLs @@ -208,7 +219,10 @@ memory://main/specs/api-design # "main" project, "specs/api-design" path memory://research/papers/crdt # "research" project ``` -The first path segment is matched against known project names. If it matches, it's used as the project scope. Otherwise pass `project` explicitly when several projects are addressable; unqualified calls are refused. +Always pass `project` explicitly, even with a project-qualified URL or one +configured project. A recognized project prefix must agree with that parameter; +it does not replace it. Use a project external ID or `workspace/project` when +names collide across workspaces. ### Using Memory URLs @@ -216,13 +230,13 @@ Memory URLs work with `bm_context` to assemble related knowledge by traversing r ```python # Get a note and its connected context -bm_context(identifier="memory://api-design-decisions") +bm_context(identifier="memory://api-design-decisions", project="") # Wildcard — gather all docs -bm_context(identifier="memory://docs/*") +bm_context(identifier="memory://docs/*", project="") # Direct read by permalink -bm_read(identifier="memory://api-design-decisions") +bm_read(identifier="memory://api-design-decisions", project="") ``` ## Before Creating a Note @@ -235,9 +249,9 @@ A single search often misses. Try the full name, abbreviations, acronyms, and ke ```python # Searching for an entity that might already exist -bm_search(query="Kubernetes Migration") -bm_search(query="k8s migration") -bm_search(query="container migration") +bm_search(query="Kubernetes Migration", project="") +bm_search(query="k8s migration", project="") +bm_search(query="container migration", project="") ``` For people, try full name and last name. For organizations, try the full name and common abbreviations. @@ -258,7 +272,8 @@ bm_edit( identifier="API Design Decisions", command="insert_after_section", section="Observations", - content="- [decision] Switched to OpenAPI 3.1 for spec generation #api" + content="- [decision] Switched to OpenAPI 3.1 for spec generation #api", + project="", ) # Fix outdated information @@ -266,7 +281,8 @@ bm_edit( identifier="API Design Decisions", command="find_replace", find_text="- [status] draft", - content="- [status] approved" + content="- [status] approved", + project="", ) # Add a new relation @@ -274,7 +290,8 @@ bm_edit( identifier="API Design Decisions", command="insert_after_section", section="Relations", - content="- depends_on [[Rate Limiter]]" + content="- depends_on [[Rate Limiter]]", + project="", ) ``` @@ -303,7 +320,8 @@ flexibility matters more. ## Relations - implements [[API Specification]] -- relates_to [[Backend Architecture]]""" +- relates_to [[Backend Architecture]]""", + project="", ) ``` @@ -321,7 +339,8 @@ bm_edit( identifier="API Design Decisions", command="insert_after_section", section="Observations", - content="- [decision] Use OpenAPI 3.1 for spec generation #api" + content="- [decision] Use OpenAPI 3.1 for spec generation #api", + project="", ) # append / prepend — add to the end of the note or the start of the body @@ -329,7 +348,8 @@ bm_edit( bm_edit( identifier="API Design Decisions", command="prepend", - content="> Updated 2026-05-28: auth approach finalized.\n" + content="> Updated 2026-05-28: auth approach finalized.\n", + project="", ) # replace_section — rewrite a named section (use for living content that stays current) @@ -337,7 +357,8 @@ bm_edit( identifier="API Design Decisions", command="replace_section", section="Summary", - content="Concise, current summary of the decision and its rationale." + content="Concise, current summary of the decision and its rationale.", + project="", ) # find_replace — swap specific text @@ -345,7 +366,8 @@ bm_edit( identifier="API Design Decisions", command="find_replace", find_text="OpenAPI 3.0", - content="OpenAPI 3.1" + content="OpenAPI 3.1", + project="", ) ``` @@ -353,18 +375,19 @@ When an edit is destructive (`replace_section`, `find_replace`), read the note f and pass its checksum, so the edit applies only to the revision you read: ```python -note = bm_read(identifier="API Design Decisions", output_format="json") +note = bm_read(identifier="API Design Decisions", output_format="json", project="") bm_edit( identifier="API Design Decisions", command="replace_section", section="Summary", content="Concise, current summary of the decision and its rationale.", - expected_checksum=note["checksum"] + expected_checksum=note["checksum"], + project="", ) ``` A checksum conflict means someone changed the note after you read it. Read it -again and redo the edit against the new text. `bm_write(overwrite=True)` takes +again and redo the edit against the new text. `bm_write(overwrite=True, project="")` takes `expected_checksum` the same way. ### Moving a Note @@ -374,7 +397,8 @@ Use `bm_move` to reorganize notes into different directories: ```python bm_move( identifier="API Design Decisions", - destination="archive/api-design-decisions.md" + destination="archive/api-design-decisions.md", + project="", ) ``` diff --git a/skills/memory-okf/SKILL.md b/skills/memory-okf/SKILL.md index 7b98a9831..0a463c8cf 100644 --- a/skills/memory-okf/SKILL.md +++ b/skills/memory-okf/SKILL.md @@ -18,6 +18,17 @@ Cloud task; locally it is `bm okf export`. Keep the project's wikilinks. They are how Basic Memory links notes, and the export converts them. +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## When to Use - Asked to prepare a project for OKF export, publishing, or handoff @@ -30,16 +41,16 @@ export converts them. ```python # Note files must end in lowercase .md -bm_find(name="*.markdown") -bm_find(name="*.MD") +bm_find(name="*.markdown", project="") +bm_find(name="*.MD", project="") # index.md and log.md belong to the wiki. A file there with note_type # "Index" or "Log" is a wiki page; anything else is a note of your own. -bm_find(name="index.md") -bm_find(name="log.md") +bm_find(name="index.md", project="") +bm_find(name="log.md", project="") # Export records relation types under `bm.okf_export`, so a note may not use it -bm_search(filters={"bm.okf_export": {"$exists": True}}) +bm_search(filters={"bm.okf_export": {"$exists": True}}, project="") ``` Page through each `bm_find` until `has_more` is false. @@ -53,15 +64,15 @@ Page through each `bm_find` until `has_more` is false. | A note uses `bm.okf_export`, or `bm` is not a mapping | Rewrite its frontmatter without that key (below) | ```python -bm_move(identifier="notes/long-form.markdown", destination="notes/long-form.md") -bm_move(identifier="notes/index.md", destination="notes/overview.md") +bm_move(identifier="notes/long-form.markdown", destination="notes/long-form.md", project="") +bm_move(identifier="notes/index.md", destination="notes/overview.md", project="") ``` `bm_move` keeps links to the note working. To rewrite frontmatter, read the note as JSON and overwrite only that revision: ```python -note = bm_read(identifier="notes/clash", output_format="json") +note = bm_read(identifier="notes/clash", output_format="json", project="") bm_write( identifier=note["file_path"], title=note["title"], @@ -69,6 +80,7 @@ bm_write( metadata={...}, # the frontmatter without bm.okf_export overwrite=True, expected_checksum=note["checksum"], + project="", ) ``` diff --git a/skills/memory-onboarding/SKILL.md b/skills/memory-onboarding/SKILL.md index b2280e6bf..eaf3e0536 100644 --- a/skills/memory-onboarding/SKILL.md +++ b/skills/memory-onboarding/SKILL.md @@ -9,6 +9,17 @@ You are guiding a person who is new to Basic Memory through building a knowledge This skill works with any LLM or assistant platform. Where platform-specific setup is needed (system prompts, project instructions), identify what YOUR environment supports and adapt the generic patterns in `references/assistant-setup.md`. +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## Why this approach Basic Memory is markdown files parsed into a knowledge graph. A pile of unstructured notes is barely better than a folder of text files. The compounding value comes from four things this skill installs from day one: @@ -46,7 +57,7 @@ Do not skip the approval gate between Phase 2 and Phase 3. Building the wrong st Before asking the user anything: -1. Confirm Basic Memory tools are available (`bm_write`, `bm_read`, `bm_search`, `bm_list`, and ideally `bm_schema(command="infer")`/`bm_schema(command="validate")`). If they aren't, stop and help the user connect Basic Memory first. +1. Confirm Basic Memory tools are available (`bm_write`, `bm_read`, `bm_search`, `bm_list`, and ideally `bm_schema(command="infer", project="")`/`bm_schema(command="validate", project="")`). If they aren't, stop and help the user connect Basic Memory first. 2. List their projects (`bm_project(command="list")`). Ask which project to build in, or whether to create a fresh one. **Every subsequent call must pass this project explicitly** — mixed-project writes are one of the most common and painful setup errors. 3. Check for existing content (`bm_find(path="/", depth=2, project="")`). Three situations: - **Empty** — greenfield, proceed normally. @@ -97,7 +108,7 @@ Build in this order — later items reference earlier ones: 4. **Index notes** → one per domain that needs one (tables of contents; not every domain does). 5. **Migrate existing notes** *(restructure path)* → execute the approved old→new mapping from Phase 2 before seeding anything: move each existing note to its new home, set its note type, add the observations its schema requires, and update indexes as notes land. Archive what doesn't fit — never delete. Phase 3 is not done while anything still sits unorganized at the root. 6. **Seed notes** → 2–3 REAL notes per domain using the examples collected in Phase 1. Never seed with placeholder data — real notes teach the format and are immediately useful; fake ones are noise the user must delete. -7. **Validate** → run `bm_schema(command="validate")` on the seed notes AND any migrated notes; fix anything it flags. Read back the router and one instruction note to confirm links resolve. +7. **Validate** → run `bm_schema(command="validate", project="")` on the seed notes AND any migrated notes; fix anything it flags. Read back the router and one instruction note to confirm links resolve. Follow the write discipline in `references/conventions.md` throughout — most importantly: search before creating anything, use exact folder casing, and watch write results for duplicate-suffixed permalinks (`-1`, `-2`). @@ -125,7 +136,7 @@ Then write a **cheat-sheet note** into their KB (`Instructions/` folder): the ph Close the onboarding by opening doors: - **Suggest 2–3 specific expansions** drawn from their deferred Phase 1 domains or natural neighbors of what they built (built tasks → suggest meetings; built finances → suggest renewals calendar; built research → suggest a reading log). Frame each as "when you're ready" — never build unrequested. -- **Maintenance cadence** — suggest a periodic (weekly/monthly) review: `bm_schema(command="diff")` for drift, scan for duplicate or orphaned notes, prune stale statuses. If their platform supports scheduled/recurring tasks, offer to set this up. +- **Maintenance cadence** — suggest a periodic (weekly/monthly) review: `bm_schema(command="diff", project="")` for drift, scan for duplicate or orphaned notes, prune stale statuses. If their platform supports scheduled/recurring tasks, offer to set this up. - **Evolution rule** — when a convention starts to chafe, change the instruction note (with a changelog row), don't silently deviate. The system stays self-describing only if the rules in it stay true. ## Reference files diff --git a/skills/memory-onboarding/references/schema-guide.md b/skills/memory-onboarding/references/schema-guide.md index ddacb3b80..b878ee6ac 100644 --- a/skills/memory-onboarding/references/schema-guide.md +++ b/skills/memory-onboarding/references/schema-guide.md @@ -107,7 +107,8 @@ description. Status moves open → in-progress → done; blocked is a holding st ## Observations - [convention] Every task carries status as an observation -- [convention] Done tasks get a close-date appended before archiving""" +- [convention] Done tasks get a close-date appended before archiving""", + project="", ) ``` @@ -120,11 +121,11 @@ Key points: ## Validation & drift -- `bm_schema(command="validate", note_type="task")` — check all notes of a type, or a single note via `identifier=`. It reports **missing required fields** and **invalid enum values** — that's the whole contract. Fields the schema doesn't declare are only counted as informational "unmatched" metadata (schemas are a subset, not a straitjacket), and scalar values are not type-checked, so a clean validate doesn't guarantee more than required-field presence and enum conformance. Use `bm_schema(command="diff")` to surface undeclared fields. -- `bm_schema(command="diff", note_type="task")` — finds drift: fields notes use that the schema doesn't define (candidates to add as optional), and schema fields nobody uses (candidates to drop). -- `bm_schema(command="infer", note_type="task")` — when notes of a type already exist without a schema, infer one from their actual structure instead of designing from scratch. +- `bm_schema(command="validate", note_type="task", project="")` — check all notes of a type, or a single note via `identifier=`. It reports **missing required fields** and **invalid enum values** — that's the whole contract. Fields the schema doesn't declare are only counted as informational "unmatched" metadata (schemas are a subset, not a straitjacket), and scalar values are not type-checked, so a clean validate doesn't guarantee more than required-field presence and enum conformance. Use `bm_schema(command="diff", project="")` to surface undeclared fields. +- `bm_schema(command="diff", note_type="task", project="")` — finds drift: fields notes use that the schema doesn't define (candidates to add as optional), and schema fields nobody uses (candidates to drop). +- `bm_schema(command="infer", note_type="task", project="")` — when notes of a type already exist without a schema, infer one from their actual structure instead of designing from scratch. -Evolution loop: `bm_schema(command="diff")` → edit the schema note (append changelog row, bump version if breaking) → `bm_schema(command="validate")` → fix outliers. Suggest the user run this monthly-ish once the system has real volume. +Evolution loop: `bm_schema(command="diff", project="")` → edit the schema note (append changelog row, bump version if breaking) → `bm_schema(command="validate", project="")` → fix outliers. Suggest the user run this monthly-ish once the system has real volume. ## Design guidelines diff --git a/skills/memory-quest/SKILL.md b/skills/memory-quest/SKILL.md index 8147b44c1..c838f86f2 100644 --- a/skills/memory-quest/SKILL.md +++ b/skills/memory-quest/SKILL.md @@ -9,6 +9,17 @@ Memory Quest's last mission checks that this assistant is set up to use Basic Me The note write *is* the verification. There is no other endpoint to call and nothing to report afterwards. +## Project scope + +Discover projects in step 1, then use the cloud project selected in step 5. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## When to Use - The user runs `/memory-quest` (or `$memory-quest`, or picks it from a skill menu) diff --git a/skills/memory-reflect/SKILL.md b/skills/memory-reflect/SKILL.md index 19a2e3a61..9d1d1fdc1 100644 --- a/skills/memory-reflect/SKILL.md +++ b/skills/memory-reflect/SKILL.md @@ -13,6 +13,17 @@ month, and puts it where someone will look for it. Inspired by sleep-time compute: memory forms best between working sessions, not during them. +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## When to Run - **Scheduled**: once or twice a day, or on a heartbeat @@ -26,22 +37,22 @@ not during them. ```python # The last reflection is the checkpoint. Titles carry date and time, so the # newest sorts first. -bm_list(path="reflections", sort="title_desc", page_size=1) +bm_list(path="reflections", sort="title_desc", page_size=1, project="") # Everything changed since that date (json gives one row per note). With no # reflection yet, use since="7d". -bm_project(command="recent", since="2026-10-13", items=["note"], output_format="json", page_size=50) +bm_project(command="recent", since="2026-10-13", items=["note"], output_format="json", page_size=50, project="") # Ask for page=2, 3, ... until has_more is false. # Read each changed note in full before judging it -bm_read(identifier="meetings/2026-10-14-launch-sync") +bm_read(identifier="meetings/2026-10-14-launch-sync", project="") ``` Timeframes count whole days, so the window can overlap the last reflection. Skip notes it lists as `reviewed`, and notes you wrote in an earlier reflection, unless someone edited them since. -`bm_project(command="recent")` looks back at most a year. If the last reflection is older +`bm_project(command="recent", project="")` looks back at most a year. If the last reflection is older than that, use `since="365d"` and record in this reflection that changes before that window were not reviewed. @@ -65,8 +76,8 @@ For each item, ask: Find the durable note for each item before writing anything: ```python -bm_search(query="launch checklist owner") -bm_context(identifier="memory://projects/launch") +bm_search(query="launch checklist owner", project="") +bm_context(identifier="memory://projects/launch", project="") ``` - **Say when it holds.** A fact with a date gets a qualifier (see @@ -91,13 +102,14 @@ bm_context(identifier="memory://projects/launch") checksum to the edit, so the edit applies only to the revision you read. ```python - note = bm_read(identifier="Launch Plan", output_format="json") + note = bm_read(identifier="Launch Plan", output_format="json", project="") bm_edit( identifier="Launch Plan", command="replace_section", section="## Owners", content="- [owner] Maya owns the launch checklist", expected_checksum=note["checksum"], + project="", ) ``` diff --git a/skills/memory-research/SKILL.md b/skills/memory-research/SKILL.md index 041379fbb..5536a1324 100644 --- a/skills/memory-research/SKILL.md +++ b/skills/memory-research/SKILL.md @@ -7,6 +7,17 @@ description: "Research an external subject on the web and synthesize it into a s Research an external subject, synthesize what you find, and create a structured Basic Memory entity — with the user's approval. +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## Workflow ### Step 1: Web Research @@ -36,8 +47,8 @@ Search for current information across multiple sources. Aim for 3-5 searches to Before proposing a new entity, search Basic Memory: ```python -bm_search(query="Acme Corp") -bm_search(query="acme") +bm_search(query="Acme Corp", project="") +bm_search(query="acme", project="") ``` Try name variations — full name, abbreviation, acronym, domain name. @@ -135,7 +146,8 @@ bm_write( - [additional observations from research findings] ## Relations -- [Link to related entities already in the knowledge graph]""" +- [Link to related entities already in the knowledge graph]""", + project="", ) ``` @@ -163,7 +175,8 @@ bm_write( - [source] Researched on YYYY-MM-DD ## Relations -- works_at [[Organization]]""" +- works_at [[Organization]]""", + project="", ) ``` @@ -192,7 +205,8 @@ bm_write( - [source] Researched on YYYY-MM-DD ## Relations -- [Link to related concepts, tools, or projects in the knowledge graph]""" +- [Link to related concepts, tools, or projects in the knowledge graph]""", + project="", ) ``` @@ -211,7 +225,8 @@ bm_edit( identifier="Acme Corp", command="insert_after_section", section="Observations", - content="- [context] Saw their demo at conference, week of 2026-02-17" + content="- [context] Saw their demo at conference, week of 2026-02-17", + project="", ) ``` diff --git a/skills/memory-schema/SKILL.md b/skills/memory-schema/SKILL.md index e72fe5957..81fd4d5b2 100644 --- a/skills/memory-schema/SKILL.md +++ b/skills/memory-schema/SKILL.md @@ -7,6 +7,17 @@ description: "Manage Basic Memory schemas: find unschemaed notes, infer and edit Manage structured note types using Basic Memory's Picoschema system. Schemas define what fields a note type should have, making notes uniform, queryable, and validatable. +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## When to Use - **New note type emerging** — you notice several notes share the same structure (meetings, people, decisions) @@ -112,12 +123,12 @@ settings: Look for clusters of notes that share structure but have no schema: -1. **Search by type**: `bm_search(note_types=["meeting"])` — if many notes share a `type` but no `schema/Meeting.md` exists, it's a candidate. +1. **Search by type**: `bm_search(note_types=["meeting"], project="")` — if many notes share a `type` but no `schema/Meeting.md` exists, it's a candidate. -2. **Infer a schema**: Use `bm_schema(command="infer")` to analyze existing notes and generate a suggested schema: +2. **Infer a schema**: Use `bm_schema(command="infer", project="")` to analyze existing notes and generate a suggested schema: ```python - bm_schema(command="infer", note_type="Meeting") - bm_schema(command="infer", note_type="Meeting", threshold=0.5) # fields in 50%+ of notes + bm_schema(command="infer", note_type="Meeting", project="") + bm_schema(command="infer", note_type="Meeting", threshold=0.5, project="") # fields in 50%+ of notes ``` The threshold (0.0–1.0) controls how common a field must be to be included. Default is usually fine; lower it to catch rarer fields. @@ -150,7 +161,8 @@ Schema for meeting notes. ## Observations - [convention] Meeting notes live in memory/meetings/ or as daily entries - [convention] Always include date and topic -- [convention] Action items should become tasks when complex""" +- [convention] Action items should become tasks when complex""", + project="", ) ``` @@ -168,13 +180,13 @@ Check how well existing notes conform to their schema: ```python # Validate all notes of a type -bm_schema(command="validate", note_type="Meeting") +bm_schema(command="validate", note_type="Meeting", project="") # Validate a single note -bm_schema(command="validate", identifier="meetings/2026-02-10-standup") +bm_schema(command="validate", identifier="meetings/2026-02-10-standup", project="") ``` -**Important:** `bm_schema(command="validate")` checks for schema fields as **observation categories** in the note body — e.g., a `status` field expects `- [status] active` as an observation. Fields stored only in frontmatter metadata won't satisfy validation. To pass cleanly, include schema fields as both frontmatter values (for metadata search) and observations (for schema validation). +**Important:** `bm_schema(command="validate", project="")` checks for schema fields as **observation categories** in the note body — e.g., a `status` field expects `- [status] active` as an observation. Fields stored only in frontmatter metadata won't satisfy validation. To pass cleanly, include schema fields as both frontmatter values (for metadata search) and observations (for schema validation). Validation reports **missing required fields** (as observation categories, or relations for entity-reference fields) and **invalid enum values**. Undeclared observation categories @@ -188,10 +200,10 @@ type-checked. ## Detecting Drift -Over time, notes evolve and schemas lag behind. Use `bm_schema(command="diff")` to find divergence: +Over time, notes evolve and schemas lag behind. Use `bm_schema(command="diff", project="")` to find divergence: ```python -bm_schema(command="diff", note_type="Meeting") +bm_schema(command="diff", note_type="Meeting", project="") ``` Diff reports: @@ -203,7 +215,7 @@ Diff reports: When note structure changes: -1. **Run diff** to see current state: `bm_schema(command="diff", note_type="Meeting")` +1. **Run diff** to see current state: `bm_schema(command="diff", note_type="Meeting", project="")` 2. **Update the schema note** via `bm_edit` with the `metadata` parameter. Top-level keys are replaced whole, so pass the complete updated `schema` map along with the new `version`: @@ -220,10 +232,11 @@ When note structure changes: "decisions?(array)": "string, decisions made", "location?": "string, where it happened" } - } + }, + project="", ) ``` -3. **Re-validate** to confirm existing notes still pass: `bm_schema(command="validate", note_type="Meeting")` +3. **Re-validate** to confirm existing notes still pass: `bm_schema(command="validate", note_type="Meeting", project="")` 4. **Fix outliers** — update notes that don't conform to the new schema ### Evolution Guidelines @@ -237,10 +250,10 @@ When note structure changes: ## Workflow Summary ``` -1. Notice repeated note structure → infer schema (bm_schema(command="infer")) +1. Notice repeated note structure → infer schema (bm_schema(command="infer", project="")) 2. Review + create schema note → write to schema/ (bm_write) -3. Validate existing notes → check conformance (bm_schema(command="validate")) +3. Validate existing notes → check conformance (bm_schema(command="validate", project="")) 4. Fix outliers → edit non-conforming notes (bm_edit) -5. Periodically check drift → detect divergence (bm_schema(command="diff")) +5. Periodically check drift → detect divergence (bm_schema(command="diff", project="")) 6. Evolve schema as needed → update schema note (bm_edit) ``` diff --git a/skills/memory-tasks/SKILL.md b/skills/memory-tasks/SKILL.md index a75e9fe38..f302ecc66 100644 --- a/skills/memory-tasks/SKILL.md +++ b/skills/memory-tasks/SKILL.md @@ -7,6 +7,17 @@ description: "Task management via Basic Memory schemas: create, track, and resum Manage work-in-progress using Basic Memory's schema system. Tasks are just notes with `type: Task` — they live in the knowledge graph, validate against a schema, and survive context compaction. +## Project scope + +If the project is unknown, discover it with `bm_project(command="list")`. +Pass a nonempty `project` on every note, folder, context and schema call, even +with one project or a qualified `memory://` URL. Use the chosen project's name, +`workspace/project`, or external ID; `` below is a placeholder for it. +Recent activity also requires `project`. Search accepts `project` for one +project, `projects` for selected projects, or `all_projects=True` explicitly. +Discovery and bundled manuals need no project. Keep the same scope when following +returned paths, paginating, or recovering from a refusal. + ## When to Use - **Starting multi-step work** (3+ steps, or anything that might outlast the context window) @@ -75,18 +86,19 @@ What future-you needs to pick up this work. Include: - Key file paths and repos involved - Decisions already made and why - What was tried and what worked/didn't -- Where to look for related context""" +- Where to look for related context""", + project="", ) ``` -**Why both frontmatter and observations?** Fields in `metadata` (stored as frontmatter) power `bm_search` with `filters`. Fields as observations (`- [status] active`) power `bm_schema(command="validate")`. Include queryable fields in both places for full coverage. +**Why both frontmatter and observations?** Fields in `metadata` (stored as frontmatter) power `bm_search` with `filters`. Fields as observations (`- [status] active`) power `bm_schema(command="validate", project="")`. Include queryable fields in both places for full coverage. ### Key Principles - **Steps are concrete and checkable** — "Implement X in file Y", not "figure out stuff" - **Context is for post-amnesia resumption** — Write it as if explaining to a smart person who knows nothing about what you've been doing - **Relations link to other entities** — `parent_task [[Other Task]]`, `related_to [[Some Note]]` -- **Note types are normalized to snake_case** — `bm_write(note_type="Task")` stores `type: task`, and `note_types=["Task"]` or `note_types=["task"]` both match it. +- **Note types are normalized to snake_case** — `bm_write(note_type="Task", project="")` stores `type: task`, and `note_types=["Task"]` or `note_types=["task"]` both match it. ## Resuming After Compaction @@ -94,7 +106,7 @@ On session start or after compaction: 1. **Search for active tasks:** ```python - bm_search(note_types=["task"], filters={"status": "active"}) + bm_search(note_types=["task"], filters={"status": "active"}, project="") ``` 2. **Read the task note** to get full context @@ -124,12 +136,13 @@ writing. Update frontmatter too, with `command="set_metadata"` and the `metadata` parameter (the body stays unchanged): ```python -task = bm_read(identifier="tasks/descriptive-task-name", output_format="json") +task = bm_read(identifier="tasks/descriptive-task-name", output_format="json", project="") bm_edit( identifier="tasks/descriptive-task-name", command="set_metadata", metadata={"current_step": 3}, - expected_checksum=task["checksum"] + expected_checksum=task["checksum"], + project="", ) ``` @@ -147,7 +160,7 @@ Add a brief summary of what was accomplished and any follow-up needed. When a compaction event is imminent: -1. Find all active tasks: `bm_search(note_types=["task"], filters={"status": "active"})` +1. Find all active tasks: `bm_search(note_types=["task"], filters={"status": "active"}, project="")` 2. For each, update: - `current_step` to reflect actual progress - `context` with everything needed to resume @@ -160,14 +173,14 @@ With BM's schema system, tasks are fully queryable: | Query | What it finds | |-------|--------------| -| `bm_search(note_types=["task"])` | All tasks | -| `bm_search(note_types=["task"], filters={"status": "active"})` | Active tasks | -| `bm_search(note_types=["task"], filters={"status": "blocked"})` | Blocked tasks | -| `bm_search(note_types=["task"], filters={"assigned_to": "claude"})` | My tasks | -| `bm_search("blockers", note_types=["task"])` | Tasks with blockers | -| `bm_search(note_types=["task"], time_kind="due", valid_overlaps="[2026-10-14,2026-10-21)")` | Tasks with a step due this week | -| `bm_schema(command="validate", note_type="Task")` | Validate all tasks against schema | -| `bm_schema(command="diff", note_type="Task")` | Detect drift between schema and actual task notes | +| `bm_search(note_types=["task"], project="")` | All tasks | +| `bm_search(note_types=["task"], filters={"status": "active"}, project="")` | Active tasks | +| `bm_search(note_types=["task"], filters={"status": "blocked"}, project="")` | Blocked tasks | +| `bm_search(note_types=["task"], filters={"assigned_to": "claude"}, project="")` | My tasks | +| `bm_search("blockers", note_types=["task"], project="")` | Tasks with blockers | +| `bm_search(note_types=["task"], time_kind="due", valid_overlaps="[2026-10-14,2026-10-21)", project="")` | Tasks with a step due this week | +| `bm_schema(command="validate", note_type="Task", project="")` | Validate all tasks against schema | +| `bm_schema(command="diff", note_type="Task", project="")` | Detect drift between schema and actual task notes | ### Due Dates @@ -188,4 +201,4 @@ also returns overdue items. - **Context > steps** — Steps tell you what to do; context tells you why and how - **Close finished tasks** — Don't leave completed work as `active` - **Link related tasks** — Use `parent_task [[X]]` or relations to connect related work -- **Schema validation is your friend** — Run `bm_schema(command="validate", note_type="Task")` periodically to catch incomplete tasks +- **Schema validation is your friend** — Run `bm_schema(command="validate", note_type="Task", project="")` periodically to catch incomplete tasks diff --git a/src/basic_memory/mcp/prompts/continue_conversation.py b/src/basic_memory/mcp/prompts/continue_conversation.py index d7d8ca02b..71153e896 100644 --- a/src/basic_memory/mcp/prompts/continue_conversation.py +++ b/src/basic_memory/mcp/prompts/continue_conversation.py @@ -64,7 +64,7 @@ async def continue_conversation( if isinstance(result, dict): results = result.get("results", []) - context_text = _format_continuation_results(results, topic) + context_text = _format_continuation_results(results, topic, project=project) result_count = len(results) else: # Error string @@ -102,9 +102,9 @@ async def continue_conversation( prompt += dedent(f""" Found {result_count} results related to '{topic}'. - 1. **Read full content** - Use `bm_read("permalink")` to dive into specific notes - 2. **Build context** - Use `bm_context("memory://path")` to see relationships - 3. **Search deeper** - Use `bm_search("{topic}")` with different filters + 1. **Read full content** - Use `bm_read("permalink", project={project!r})` to dive into specific notes + 2. **Build context** - Use `bm_context("memory://path", project={project!r})` to see relationships + 3. **Search deeper** - Use `bm_search({topic!r}, project={project!r})` with different filters If this conversation produces a decision or insight worth keeping, offer to save it with `bm_write`. @@ -117,16 +117,16 @@ async def continue_conversation( topic tracked, offer to start a note with `bm_write`. """) else: - prompt += dedent(""" - 1. **Explore specific items** - Use `bm_read("permalink")` to dive deeper - 2. **Search for topics** - Use `bm_search("topic")` to find specific content - 3. **Build context** - Use `bm_context("memory://path")` to see relationships + prompt += dedent(f""" + 1. **Explore specific items** - Use `bm_read("permalink", project={project!r})` to dive deeper + 2. **Search for topics** - Use `bm_search("topic", project={project!r})` to find specific content + 3. **Build context** - Use `bm_context("memory://path", project={project!r})` to see relationships """) return prompt -def _format_continuation_results(results: list[dict[str, Any]], topic: str) -> str: +def _format_continuation_results(results: list[dict[str, Any]], topic: str, *, project: str) -> str: """Format search result dicts for conversation continuation context.""" if not results: return f"No previous context found for '{topic}'." @@ -140,7 +140,7 @@ def _format_continuation_results(results: list[dict[str, Any]], topic: str) -> s lines.append(f"### {title}") if permalink: lines.append(f"permalink: {permalink}") - lines.append(f'Read with: `bm_read("{permalink}")`') + lines.append(f"Read with: `bm_read({permalink!r}, project={project!r})`") content = item.get("content") if content: content = content[:300] + "..." if len(content) > 300 else content diff --git a/src/basic_memory/mcp/prompts/search.py b/src/basic_memory/mcp/prompts/search.py index 0b6618f20..51d2ef2fc 100644 --- a/src/basic_memory/mcp/prompts/search.py +++ b/src/basic_memory/mcp/prompts/search.py @@ -49,6 +49,11 @@ async def search_prompt( # Use json format to get structured data for result counting and formatting # Prompts preserve their default-project workflow; bm_search requires explicit scope. project = await resolve_project_parameter(project=project, context=context) + if project is None: + return ( + "Choose a project with bm_project(command='list'), then search with an " + "explicit project name or external id." + ) result = await bm_search( query=query, since=timeframe, project=project, context=context, output_format="json" ) @@ -78,10 +83,10 @@ async def search_prompt( Based on these {result_count} results, you can: - 1. **Read a specific note** - Use `bm_read("permalink")` to see full content - 2. **Build context** - Use `bm_context("memory://path")` to see relationships - 3. **Refine search** - Use `bm_search("refined query")` to narrow results - 4. **Check recent activity** - Use `bm_project(command="recent", since="7d")` for recent changes + 1. **Read a specific note** - Use `bm_read("permalink", project={project!r})` to see full content + 2. **Build context** - Use `bm_context("memory://path", project={project!r})` to see relationships + 3. **Refine search** - Use `bm_search("refined query", project={project!r})` to narrow results + 4. **Check recent activity** - Use `bm_project(command="recent", since="7d", project={project!r})` for recent changes """) diff --git a/tests/mcp/test_required_project.py b/tests/mcp/test_required_project.py index 643978955..4b8dbde1e 100644 --- a/tests/mcp/test_required_project.py +++ b/tests/mcp/test_required_project.py @@ -3,6 +3,7 @@ import ast import importlib import json +import re from typing import Any from unittest.mock import AsyncMock @@ -162,17 +163,47 @@ async def test_chatgpt_fetch_reports_unresolved_scope(monkeypatch): @pytest.mark.asyncio @pytest.mark.parametrize( - ("module_name", "prompt_name"), + ("module_name", "prompt_name", "arguments"), [ - ("continue_conversation", "continue_conversation"), - ("recent_activity", "recent_activity_prompt"), + ("continue_conversation", "continue_conversation", {}), + ("recent_activity", "recent_activity_prompt", {}), + ("search", "search_prompt", {"query": "plan"}), ], ) async def test_prompts_discover_before_calling_tools_when_no_project_resolves( - monkeypatch, module_name, prompt_name + monkeypatch, module_name, prompt_name, arguments ): module = importlib.import_module(f"basic_memory.mcp.prompts.{module_name}") monkeypatch.setattr(module, "resolve_project_parameter", AsyncMock(return_value=None)) - result = await getattr(module, prompt_name)() + result = await getattr(module, prompt_name)(**arguments) assert "bm_project(command='list')" in result assert "explicit project" in result + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("module_name", "prompt_name", "arguments"), + [ + ("search", "search_prompt", {"query": "scopepromptnonce"}), + ("continue_conversation", "continue_conversation", {"topic": "scopepromptnonce"}), + ("continue_conversation", "continue_conversation", {"topic": "nomatchuniqueword"}), + ("continue_conversation", "continue_conversation", {}), + ("recent_activity", "recent_activity_prompt", {}), + ], +) +async def test_every_saved_prompt_followup_call_carries_its_scope( + client, test_project, module_name, prompt_name, arguments +): + await tools.bm_write( + identifier="notes/plan.md", content="# scopepromptnonce", project=test_project.name + ) + module = importlib.import_module(f"basic_memory.mcp.prompts.{module_name}") + result = await getattr(module, prompt_name)(project=test_project.name, **arguments) + calls = re.findall(r"`(bm_(?:read|context|search|project)\([^`\n]*\))`", result) + assert calls + for example in calls: + call = ast.parse(example, mode="eval").body + assert isinstance(call, ast.Call) + scope = [keyword.value for keyword in call.keywords if keyword.arg == "project"] + assert len(scope) == 1, example + assert ast.literal_eval(scope[0]) == test_project.name From a25097e01a471c52a042443e5aad0e9f55552651 Mon Sep 17 00:00:00 2001 From: phernandez Date: Wed, 28 Oct 2026 17:17:21 -0500 Subject: [PATCH 3/3] test(mcp): align integration flows with explicit project scope Signed-off-by: phernandez --- .../mcp/test_compact_search_integration.py | 2 +- .../test_default_project_mode_integration.py | 50 ++++++++++------- .../mcp/test_posix_default_integration.py | 31 ++++++++--- .../test_single_project_mcp_integration.py | 10 +++- .../test_workspace_permalink_integration.py | 55 +++++++++++-------- 5 files changed, 97 insertions(+), 51 deletions(-) diff --git a/test-int/mcp/test_compact_search_integration.py b/test-int/mcp/test_compact_search_integration.py index 0279d34cb..4e0be06ee 100644 --- a/test-int/mcp/test_compact_search_integration.py +++ b/test-int/mcp/test_compact_search_integration.py @@ -59,7 +59,7 @@ async def test_compact_search_can_discover_then_read_notes( selected = compact["results"][0] read = await client.call_tool( "bm_read", - {"identifier": selected["permalink"]} + {"identifier": selected["permalink"], "project": test_project.name} if all_projects and observations else {"identifier": selected["external_id"], "project": test_project.name}, ) diff --git a/test-int/mcp/test_default_project_mode_integration.py b/test-int/mcp/test_default_project_mode_integration.py index 9b1f26e5a..d61578ddc 100644 --- a/test-int/mcp/test_default_project_mode_integration.py +++ b/test-int/mcp/test_default_project_mode_integration.py @@ -1,9 +1,8 @@ """ -Integration tests for default project resolution. +Integration tests for explicit MCP scope with configured project defaults. -Tests the default_project configuration that allows tools to automatically -use the default_project when no project parameter is specified, covering -parameter resolution hierarchy and fallback behavior. +Defaults and server constraints still route scoped requests. They cannot supply +a missing required tool argument. """ import os @@ -20,8 +19,8 @@ @pytest.mark.asyncio -async def test_default_project_write_note(mcp_server, app, test_project): - """Test that write_note uses default project when no project specified.""" +async def test_explicit_write_in_default_project(mcp_server, app, test_project): + """Explicit scope selects the configured default project.""" mock_config = BasicMemoryConfig( default_project=test_project.name, @@ -30,12 +29,18 @@ async def test_default_project_write_note(mcp_server, app, test_project): with patch.object(ConfigManager, "config", mock_config): async with Client(mcp_server) as client: + with pytest.raises(ToolError, match="Missing required keyword only argument"): + await client.call_tool( + "bm_write", + {"title": "Unscoped write", "content": "Must select the default explicitly."}, + ) result = await client.call_tool( "bm_write", { + "project": test_project.name, "title": "Default Mode Test", "directory": "test", - "content": "# Default Mode Test\n\nThis should use the default project automatically.", + "content": "# Default Mode Test\n\nThis explicitly selects the configured default project.", "tags": "default,mode,test", }, ) @@ -94,24 +99,23 @@ async def test_explicit_project_overrides_default( @pytest.mark.asyncio -async def test_no_config_default_falls_back_to_db(mcp_server, app, test_project): - """When ConfigManager has no default_project, tools fall back to the database is_default flag.""" +async def test_explicit_write_without_config_default(mcp_server, app, test_project): + """Explicit scope works without a configured default.""" mock_config = BasicMemoryConfig( default_project=None, # No config default projects={test_project.name: test_project.path}, ) - # test_project has is_default=True in the database, so write_note should - # resolve to it via the API fallback in resolve_project_parameter. with patch.object(ConfigManager, "config", mock_config): async with Client(mcp_server) as client: result = await client.call_tool( "bm_write", { + "project": test_project.name, "title": "DB Fallback Test", "directory": "test", - "content": "# DB Fallback Test\n\nShould resolve to the database default project.", + "content": "# DB Fallback Test\n\nSelect the database default project explicitly.", }, ) @@ -156,6 +160,7 @@ async def test_cli_constraint_overrides_default_project( result = await client.call_tool( "bm_write", { + "project": other_project.name, "title": "CLI Constraint Test", "directory": "test", "content": "# CLI Constraint Test\n\nThis should use CLI constrained project.", @@ -174,8 +179,8 @@ async def test_cli_constraint_overrides_default_project( @pytest.mark.asyncio -async def test_default_project_read_note(mcp_server, app, test_project): - """Test that read_note works with default_project.""" +async def test_explicit_read_in_default_project(mcp_server, app, test_project): + """Explicit scope supports read-after-write in the default project.""" mock_config = BasicMemoryConfig( default_project=test_project.name, @@ -187,6 +192,7 @@ async def test_default_project_read_note(mcp_server, app, test_project): await client.call_tool( "bm_write", { + "project": test_project.name, "title": "Read Test Note", "directory": "test", "content": "# Read Test Note\n\nThis note will be read back.", @@ -195,7 +201,11 @@ async def test_default_project_read_note(mcp_server, app, test_project): result = await client.call_tool( "bm_read", - {"identifier": "Read Test Note", "include_frontmatter": False}, + { + "identifier": "Read Test Note", + "include_frontmatter": False, + "project": test_project.name, + }, ) assert len(result.content) == 1 @@ -206,8 +216,8 @@ async def test_default_project_read_note(mcp_server, app, test_project): @pytest.mark.asyncio -async def test_default_project_edit_note(mcp_server, app, test_project): - """Test that edit_note works with default_project.""" +async def test_explicit_edit_in_default_project(mcp_server, app, test_project): + """Explicit scope supports edits in the default project.""" mock_config = BasicMemoryConfig( default_project=test_project.name, @@ -219,6 +229,7 @@ async def test_default_project_edit_note(mcp_server, app, test_project): await client.call_tool( "bm_write", { + "project": test_project.name, "title": "Edit Test Note", "directory": "test", "content": "# Edit Test Note\n\nOriginal content.", @@ -228,6 +239,7 @@ async def test_default_project_edit_note(mcp_server, app, test_project): result = await client.call_tool( "bm_edit", { + "project": test_project.name, "identifier": "Edit Test Note", "command": "append", "content": "\n\n## Added Content\n\nThis was added via edit_note.", @@ -245,7 +257,7 @@ async def test_default_project_edit_note(mcp_server, app, test_project): async def test_project_resolution_hierarchy( mcp_server, app, test_project, config_home, engine_factory ): - """Test the complete three-tier project resolution hierarchy.""" + """Explicit scope is required while server constraints retain routing priority.""" engine, session_maker = engine_factory @@ -322,7 +334,7 @@ async def test_project_resolution_hierarchy( # Multiple addressable projects require an explicit scope even with a default. with patch.object(ConfigManager, "config", mock_config): async with Client(mcp_server) as client: - with pytest.raises(ToolError, match="no project specified"): + with pytest.raises(ToolError, match="Missing required keyword only argument"): await client.call_tool( "bm_write", { diff --git a/test-int/mcp/test_posix_default_integration.py b/test-int/mcp/test_posix_default_integration.py index 8e1d7e40e..5428d838f 100644 --- a/test-int/mcp/test_posix_default_integration.py +++ b/test-int/mcp/test_posix_default_integration.py @@ -44,7 +44,7 @@ async def test_posix_registration_over_mcp(mcp_server, config_manager, setting, @pytest.mark.asyncio async def test_posix_default_navigation_workflow(mcp_server, app, test_project) -> None: - """Follow advertised mount and result paths, then scan a bounded note window.""" + """Discover projects, follow scoped result paths, and scan a bounded note window.""" async with Client(mcp_server) as client: await client.call_tool( "bm_write", @@ -56,22 +56,38 @@ async def test_posix_default_navigation_workflow(mcp_server, app, test_project) "project": test_project.name, }, ) - mounts = await client.call_tool("bm_list", {"path": "/", "output_format": "json"}) - mount = next(row for row in mounts.data["nodes"] if row["name"] == test_project.name) - note_dir = f"{mount['directory_path']}/notes" - listing = await client.call_tool("bm_list", {"path": note_dir, "output_format": "json"}) + projects = await client.call_tool("bm_project", {"command": "list"}) + assert test_project.name in str(projects.data) + root = await client.call_tool( + "bm_list", {"path": "/", "project": test_project.name, "output_format": "json"} + ) + assert any(row["name"] == "notes" for row in root.data["nodes"]) + note_dir = "notes" + listing = await client.call_tool( + "bm_list", {"path": note_dir, "project": test_project.name, "output_format": "json"} + ) note_path = listing.data["nodes"][0]["file_path"] - full = await client.call_tool("bm_read", {"identifier": note_path, "output_format": "json"}) + full = await client.call_tool( + "bm_read", + {"identifier": note_path, "project": test_project.name, "output_format": "json"}, + ) assert "retry the task" in full.data["content"] found = await client.call_tool( - "bm_find", {"path": note_dir, "name": "*.md", "output_format": "json"} + "bm_find", + { + "path": note_dir, + "name": "*.md", + "project": test_project.name, + "output_format": "json", + }, ) assert found.data["nodes"][0]["file_path"] == note_path projected = await client.call_tool( "bm_find", { "path": note_dir, + "project": test_project.name, "filters": {"status": "active"}, "fields": ["priority"], "output_format": "json", @@ -96,6 +112,7 @@ async def test_posix_default_navigation_workflow(mcp_server, app, test_project) "bm_read", { "identifier": note_path, + "project": test_project.name, "start_line": window["start_line"], "end_line": window["end_line"], "output_format": "json", diff --git a/test-int/mcp/test_single_project_mcp_integration.py b/test-int/mcp/test_single_project_mcp_integration.py index 7cfa11e1e..4ebc77917 100644 --- a/test-int/mcp/test_single_project_mcp_integration.py +++ b/test-int/mcp/test_single_project_mcp_integration.py @@ -9,6 +9,7 @@ import os import pytest from fastmcp import Client +from fastmcp.exceptions import ToolError @pytest.mark.asyncio @@ -310,10 +311,15 @@ async def test_constraint_with_invalid_project_override(mcp_server, app, test_pr try: async with Client(mcp_server) as client: - # Try various invalid project names - should all be overridden + # Blank scope fails validation even when the server is constrained. + with pytest.raises(ToolError, match="at least 1 character"): + await client.call_tool( + "bm_write", {"project": "", "title": "Blank scope", "content": "Rejected"} + ) + + # Nonempty project arguments are routed through the server constraint. invalid_projects = [ "non-existent-project", - "", "project-with-special-chars!@#", "a" * 100, # Very long name ] diff --git a/test-int/mcp/test_workspace_permalink_integration.py b/test-int/mcp/test_workspace_permalink_integration.py index ee9c6746d..b506f1e75 100644 --- a/test-int/mcp/test_workspace_permalink_integration.py +++ b/test-int/mcp/test_workspace_permalink_integration.py @@ -192,14 +192,13 @@ async def _read_json( mcp_server, *, identifier: str, - project: str | None = None, + project: str, ) -> dict[str, Any]: arguments = { "identifier": identifier, "output_format": "json", } - if project is not None: - arguments["project"] = project + arguments["project"] = project return await _call_json(mcp_server, "bm_read", arguments) @@ -207,15 +206,14 @@ async def _search_single_permalink( mcp_server, *, title: str, - project: str | None = None, + project: str, ) -> str: arguments = { "query": title, "mode": "text", "output_format": "json", } - if project is not None: - arguments["project"] = project + arguments["project"] = project payload = await _call_json(mcp_server, "bm_search", arguments) matching_results = [ @@ -232,15 +230,14 @@ async def _search_permalink_exact( *, permalink: str, title: str, - project: str | None = None, + project: str, ) -> str: arguments = { - "query": permalink if project is not None else f"memory://{permalink}", + "query": f"memory://{permalink}", "mode": "permalink", "output_format": "json", } - if project is not None: - arguments["project"] = project + arguments["project"] = project payload = await _call_json(mcp_server, "bm_search", arguments) matching_results = [ @@ -288,6 +285,7 @@ async def test_memory_search_normalizes_display_project_prefix( "bm_search", { "query": f"memory://{prefix}/{suffix}", + "project": project, "output_format": "json", }, ) @@ -324,13 +322,13 @@ async def test_local_short_permalink_round_trips_when_project_is_supplied( @pytest.mark.asyncio @pytest.mark.parametrize("include_project", [True, False]) -async def test_local_project_permalink_routes_without_project_argument( +async def test_local_project_permalink_round_trips_with_explicit_project( mcp_server, alternate_project, app_config, include_project, ): - """Local project-qualified IDs carry enough route context for search/read.""" + """Local qualified IDs round-trip with matching explicit project scope.""" _save_permalink_config(app_config, include_project=include_project, default_project=None) title = "Local Project Permalink" @@ -344,13 +342,16 @@ async def test_local_project_permalink_routes_without_project_argument( assert ( await _search_permalink_exact( mcp_server, + project=alternate_project.name, permalink=qualified_permalink, title=title, ) == expected_permalink ) - project_read = await _read_json(mcp_server, identifier=qualified_permalink) + project_read = await _read_json( + mcp_server, project=alternate_project.name, identifier=qualified_permalink + ) assert project_read["permalink"] == expected_permalink @@ -390,14 +391,14 @@ async def test_personal_cloud_short_permalink_round_trips_when_project_is_suppli @pytest.mark.asyncio -async def test_personal_cloud_project_permalink_routes_without_project_argument( +async def test_personal_cloud_project_permalink_round_trips_with_explicit_project( mcp_server, alternate_project, app_config, personal_workspace, route_workspaces, ): - """Legacy project-qualified cloud IDs carry enough route context.""" + """Legacy cloud IDs round-trip with matching explicit project scope.""" _save_permalink_config(app_config, include_project=True, default_project=None) title = "Personal Cloud Project Permalink" @@ -411,13 +412,16 @@ async def test_personal_cloud_project_permalink_routes_without_project_argument( assert ( await _search_permalink_exact( mcp_server, + project=alternate_project.name, permalink=expected_permalink, title=title, ) == expected_permalink ) - project_read = await _read_json(mcp_server, identifier=expected_permalink) + project_read = await _read_json( + mcp_server, project=alternate_project.name, identifier=expected_permalink + ) assert project_read["permalink"] == expected_permalink @@ -457,14 +461,14 @@ async def test_team_short_permalink_round_trips_when_project_is_supplied( @pytest.mark.asyncio -async def test_team_project_permalink_routes_without_project_argument( +async def test_team_project_permalink_round_trips_with_explicit_project( mcp_server, alternate_project, app_config, team_workspace, route_workspaces, ): - """Team project-qualified IDs carry enough route context for search/read.""" + """Team project-qualified IDs round-trip with explicit project scope.""" _save_permalink_config(app_config, include_project=True, default_project=None) title = "Team Project Permalink" @@ -478,12 +482,15 @@ async def test_team_project_permalink_routes_without_project_argument( assert ( await _search_permalink_exact( mcp_server, + project=alternate_project.name, permalink=expected_permalink, title=title, ) == expected_permalink ) - project_read = await _read_json(mcp_server, identifier=expected_permalink) + project_read = await _read_json( + mcp_server, project=alternate_project.name, identifier=expected_permalink + ) assert project_read["permalink"] == expected_permalink @@ -496,7 +503,7 @@ async def test_team_workspace_permalink_routes_to_specific_workspace( team_workspace, route_workspaces, ): - """Workspace-qualified IDs route to the project in that workspace.""" + """Workspace-qualified IDs round-trip with matching explicit workspace scope.""" _save_permalink_config(app_config, include_project=True, default_project=None) team_project = f"{team_workspace.slug}/{test_project.name}" @@ -511,13 +518,16 @@ async def test_team_workspace_permalink_routes_to_specific_workspace( assert ( await _search_permalink_exact( mcp_server, + project=team_project, permalink=expected_permalink, title=title, ) == expected_permalink ) - workspace_read = await _read_json(mcp_server, identifier=expected_permalink) + workspace_read = await _read_json( + mcp_server, project=team_project, identifier=expected_permalink + ) assert workspace_read["permalink"] == expected_permalink @@ -529,7 +539,7 @@ async def test_write_note_by_project_id_qualifies_permalink_when_headers_not_for team_workspace, route_workspaces, ): - """MCP writes should return self-routing IDs even if the API omits slug headers.""" + """MCP writes preserve workspace-qualified IDs even if the API omits slug headers.""" _save_permalink_config(app_config, include_project=True, default_project=None) title = "Project Id Workspace Permalink" @@ -552,6 +562,7 @@ async def test_write_note_by_project_id_qualifies_permalink_when_headers_not_for workspace_read = await _read_json( mcp_server, + project=test_project.external_id, identifier=f"memory://{write_payload['permalink']}", ) assert workspace_read["title"] == title