From 8322d33d180de3fb7ec5b17e523d17713e83d8aa Mon Sep 17 00:00:00 2001 From: phernandez Date: Tue, 8 Sep 2026 01:24:12 -0500 Subject: [PATCH 1/5] fix(mcp): preserve overwrite refusal details Signed-off-by: phernandez --- src/basic_memory/mcp/tools/write_note.py | 46 ++++++++-------- test-int/cli/test_locked_note_refusals.py | 42 +++++++++++++++ test-int/mcp/test_locked_note_results.py | 66 +++++++++++++++++++++++ 3 files changed, 129 insertions(+), 25 deletions(-) create mode 100644 test-int/cli/test_locked_note_refusals.py create mode 100644 test-int/mcp/test_locked_note_results.py diff --git a/src/basic_memory/mcp/tools/write_note.py b/src/basic_memory/mcp/tools/write_note.py index 70cfca64f..712d55c51 100644 --- a/src/basic_memory/mcp/tools/write_note.py +++ b/src/basic_memory/mcp/tools/write_note.py @@ -470,31 +470,27 @@ async def write_note( return _format_overwrite_error(title, entity.permalink, active_project.name) logger.debug(f"Entity exists, updating instead permalink={entity.permalink}") - try: - if not entity.permalink: - raise ValueError( - "Entity permalink is required for updates" - ) # pragma: no cover - # Resolve the conflicting entity by file_path with strict=True. - # The 409 came from a file_service.exists(file_path) check, so this - # file_path is the authoritative key for the canonical row. Resolving - # by permalink with fuzzy fallback (the previous behavior) could pick - # an orphan with a similar permalink — especially in workspace-prefixed - # palaces where the client-built permalink omits the workspace slug — - # causing the update to write to the wrong row and the next call to - # mint a -1/-2 suffix on the canonical entity. - # POSIX-normalize so Windows clients send the same form the server stores. - file_path_identifier = Path(entity.file_path).as_posix() - entity_id = await knowledge_client.resolve_entity( - file_path_identifier, strict=True - ) - result = await knowledge_client.update_entity( - entity_id, entity.model_dump() - ) - action = "Updated" - except Exception as update_error: # pragma: no cover - # Re-raise the original error if update also fails - raise e from update_error # pragma: no cover + # Report the attempted replacement's failure, not the create conflict + # that selected this path (for example, a locked-note refusal). + if not entity.permalink: + raise ValueError( + "Entity permalink is required for updates" + ) # pragma: no cover + # Resolve the conflicting entity by file_path with strict=True. + # The 409 came from a file_service.exists(file_path) check, so this + # file_path is the authoritative key for the canonical row. Resolving + # by permalink with fuzzy fallback (the previous behavior) could pick + # an orphan with a similar permalink — especially in workspace-prefixed + # palaces where the client-built permalink omits the workspace slug — + # causing the update to write to the wrong row and the next call to + # mint a -1/-2 suffix on the canonical entity. + # POSIX-normalize so Windows clients send the same form the server stores. + file_path_identifier = Path(entity.file_path).as_posix() + entity_id = await knowledge_client.resolve_entity( + file_path_identifier, strict=True + ) + result = await knowledge_client.update_entity(entity_id, entity.model_dump()) + action = "Updated" else: # Re-raise if it's not a conflict error raise # pragma: no cover diff --git a/test-int/cli/test_locked_note_refusals.py b/test-int/cli/test_locked_note_refusals.py new file mode 100644 index 000000000..5c013dac3 --- /dev/null +++ b/test-int/cli/test_locked_note_refusals.py @@ -0,0 +1,42 @@ +"""A refused overwrite must exit unsuccessfully and explain the note lock.""" + +import json +from pathlib import Path + +from fastapi import FastAPI +from typer.testing import CliRunner + +from basic_memory.cli.main import app as cli_app +from basic_memory.models import Project + + +def test_overwrite_reports_lock_and_exits_nonzero(app: FastAPI, test_project: Project) -> None: + runner = CliRunner() + arguments = [ + "tool", + "write-note", + "--project", + test_project.name, + "--title", + "Protected Runbook", + "--folder", + "protected", + ] + created = runner.invoke( + cli_app, [*arguments, "--content", "---\nlocked: true\n---\n\nKeep this exact content.\n"] + ) + assert created.exit_code == 0, created.output + note = json.loads(created.stdout) + path = Path(test_project.path) / note["file_path"] + original = path.read_bytes() + refused = runner.invoke(cli_app, [*arguments, "--content", "Replacement", "--overwrite"]) + assert refused.exit_code != 0 + # Debug logging may include the initial create conflict. Check the CLI's + # actual failure message so logs cannot mask a misleading final result. + errors = [ + line for line in refused.stderr.splitlines() if line.startswith("Error during write_note:") + ] + assert len(errors) == 1, refused.output + assert "locked: true" in errors[0] + assert "Note already exists" not in errors[0] + assert path.read_bytes() == original diff --git a/test-int/mcp/test_locked_note_results.py b/test-int/mcp/test_locked_note_results.py new file mode 100644 index 000000000..047744542 --- /dev/null +++ b/test-int/mcp/test_locked_note_results.py @@ -0,0 +1,66 @@ +"""Locked-note refusals must reach the agent through the real MCP result.""" + +import json +from pathlib import Path +from typing import Literal + +from fastapi import FastAPI +from fastmcp import Client, FastMCP +from mcp.types import TextContent +import pytest + +from basic_memory.models import Project + + +@pytest.mark.asyncio +@pytest.mark.parametrize("output_format", ["text", "json"]) +@pytest.mark.parametrize("operation", ["edit_note", "write_note", "delete_note"]) +async def test_locked_note_mutation_returns_visible_refusal( + mcp_server: FastMCP, + app: FastAPI, + test_project: Project, + output_format: Literal["text", "json"], + operation: Literal["edit_note", "write_note", "delete_note"], +) -> None: + async with Client(mcp_server) as client: + created = await client.call_tool( + "write_note", + { + "project": test_project.name, + "title": "Protected Runbook", + "directory": "protected", + "content": "---\nlocked: true\n---\n\nKeep this exact content.\n", + "output_format": "json", + }, + ) + assert isinstance(created.content[0], TextContent) + note = json.loads(created.content[0].text) + path = Path(test_project.path) / note["file_path"] + original = path.read_bytes() + arguments: dict[str, object] = { + "project": test_project.name, + "output_format": output_format, + } + if operation == "write_note": + arguments.update( + title="Protected Runbook", + directory="protected", + content="Replacement", + overwrite=True, + ) + else: + arguments["identifier"] = note["permalink"] + if operation == "edit_note": + arguments.update(operation="append", content="Sneaky edit") + result = await client.call_tool(operation, arguments, raise_on_error=False) + assert isinstance(result.content[0], TextContent) + refusal = result.content[0].text + assert "locked: true" in refusal + if output_format == "json" and not result.is_error: + payload = json.loads(refusal) + assert payload["error"] + assert not payload.get("success") + assert payload.get("checksum") is None + else: + assert result.is_error or "error" in refusal.lower() or "failed" in refusal.lower() + assert path.read_bytes() == original From 735301d8ac3d6b4fe2c3b6b7453bda48b4ebcd3b Mon Sep 17 00:00:00 2001 From: phernandez Date: Tue, 8 Sep 2026 08:54:31 -0500 Subject: [PATCH 2/5] fix(mcp): remove obsolete overwrite permalink prerequisite Signed-off-by: phernandez --- src/basic_memory/mcp/tools/write_note.py | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/src/basic_memory/mcp/tools/write_note.py b/src/basic_memory/mcp/tools/write_note.py index 712d55c51..92a1e3f8b 100644 --- a/src/basic_memory/mcp/tools/write_note.py +++ b/src/basic_memory/mcp/tools/write_note.py @@ -470,25 +470,16 @@ async def write_note( return _format_overwrite_error(title, entity.permalink, active_project.name) logger.debug(f"Entity exists, updating instead permalink={entity.permalink}") - # Report the attempted replacement's failure, not the create conflict - # that selected this path (for example, a locked-note refusal). - if not entity.permalink: - raise ValueError( - "Entity permalink is required for updates" - ) # pragma: no cover - # Resolve the conflicting entity by file_path with strict=True. - # The 409 came from a file_service.exists(file_path) check, so this - # file_path is the authoritative key for the canonical row. Resolving - # by permalink with fuzzy fallback (the previous behavior) could pick - # an orphan with a similar permalink — especially in workspace-prefixed - # palaces where the client-built permalink omits the workspace slug — - # causing the update to write to the wrong row and the next call to - # mint a -1/-2 suffix on the canonical entity. + # The create conflict identifies an existing file. Resolve its path + # strictly, then update by the returned UUID; no permalink is required. + # Fuzzy resolution could select a different note with a similar identity. # POSIX-normalize so Windows clients send the same form the server stores. file_path_identifier = Path(entity.file_path).as_posix() entity_id = await knowledge_client.resolve_entity( file_path_identifier, strict=True ) + # Propagate the replacement failure (such as a locked-note refusal) + # instead of masking it with the initial create conflict. result = await knowledge_client.update_entity(entity_id, entity.model_dump()) action = "Updated" else: From 1b2ecc102da8935e1e217e4aa254e04a426f92e7 Mon Sep 17 00:00:00 2001 From: phernandez Date: Tue, 8 Sep 2026 09:53:24 -0500 Subject: [PATCH 3/5] fix(mcp): unify note writes with typed outcomes Signed-off-by: phernandez --- src/basic_memory/api/v2/routers/__init__.py | 3 + .../api/v2/routers/note_write_router.py | 118 ++++++++ src/basic_memory/man/man3/write-note(3).md | 7 + src/basic_memory/mcp/clients/knowledge.py | 20 ++ src/basic_memory/mcp/tools/write_note.py | 97 ++++--- src/basic_memory/schemas/v2/note_write.py | 49 ++++ .../services/note_content_writes.py | 270 +++++++++++++----- .../services/note_write_outcomes.py | 49 ++++ test-int/mcp/test_moved_note_overwrite.py | 92 ++++++ test-int/mcp/test_write_note_integration.py | 22 +- test-int/test_note_write_outcomes.py | 134 +++++++++ tests/mcp/test_tool_write_note.py | 38 +-- 12 files changed, 720 insertions(+), 179 deletions(-) create mode 100644 src/basic_memory/api/v2/routers/note_write_router.py create mode 100644 src/basic_memory/schemas/v2/note_write.py create mode 100644 src/basic_memory/services/note_write_outcomes.py create mode 100644 test-int/mcp/test_moved_note_overwrite.py create mode 100644 test-int/test_note_write_outcomes.py diff --git a/src/basic_memory/api/v2/routers/__init__.py b/src/basic_memory/api/v2/routers/__init__.py index 39a0de10f..29015ba37 100644 --- a/src/basic_memory/api/v2/routers/__init__.py +++ b/src/basic_memory/api/v2/routers/__init__.py @@ -13,6 +13,9 @@ from basic_memory.api.v2.routers.importer_router import router as importer_router from basic_memory.api.v2.routers.schema_router import router as schema_router from basic_memory.api.v2.routers.inspect_router import router as inspect_router +from basic_memory.api.v2.routers.note_write_router import router as note_write_router + +knowledge_router.include_router(note_write_router) __all__ = [ "accepted_content_router", diff --git a/src/basic_memory/api/v2/routers/note_write_router.py b/src/basic_memory/api/v2/routers/note_write_router.py new file mode 100644 index 000000000..9dfdb3c4e --- /dev/null +++ b/src/basic_memory/api/v2/routers/note_write_router.py @@ -0,0 +1,118 @@ +"""One path-addressed write, with expected outcomes preserved across HTTP.""" + +from dataclasses import asdict +from typing import Annotated, assert_never + +from fastapi import APIRouter, HTTPException, Path + +from basic_memory.deps import ( + AppConfigDep, + EntityRepositoryV2ExternalDep, + EntityVectorSyncSchedulerDep, + NoteContentMaterializationProviderDep, + NoteContentMutationServiceDep, + ProjectExternalIdPathDep, + ProjectRepositoryDep, + RelationResolutionSchedulerDep, + SessionMakerDep, +) +from basic_memory.runtime.note_content import runtime_note_content_payload_as_dict +from basic_memory.schemas.v2.entity import EntityResponseV2 +from basic_memory.schemas.v2.note_write import ( + NoteAlreadyExists, + NoteCreated, + NoteLocked, + NoteTargetMoved, + NoteUpdated, + WriteNoteRequest, + WriteNoteResponse, +) +from basic_memory.services.note_content_writes import ( + NoteContentMutationServiceError, + note_content_mutation_error_from_rejection, +) +from basic_memory.services.note_write_outcomes import ( + AlreadyExists, + Created, + Locked, + Rejected, + TargetMoved, + Updated, +) +from basic_memory.utils import build_permalink_resolution_candidates +from basic_memory.workspace_context import current_workspace_permalink_context + +router = APIRouter() + + +@router.post("/write", response_model=WriteNoteResponse) +async def write_note( + data: WriteNoteRequest, + project_id: ProjectExternalIdPathDep, + project_external_id: Annotated[str, Path(alias="project_id")], + project_repository: ProjectRepositoryDep, + entity_repository: EntityRepositoryV2ExternalDep, + session_maker: SessionMakerDep, + note_content_mutation_service: NoteContentMutationServiceDep, + note_content_materialization_provider: NoteContentMaterializationProviderDep, + vector_sync_scheduler: EntityVectorSyncSchedulerDep, + relation_resolution_scheduler: RelationResolutionSchedulerDep, + app_config: AppConfigDep, +) -> WriteNoteResponse: + """Create at the requested path or replace the note that currently owns it.""" + # Release the read connection before the mutation opens its own transaction. + async with session_maker() as session: + project = await project_repository.get_by_id(session, project_id) + if project is None: + raise HTTPException(status_code=404, detail="Project not found") + workspace = current_workspace_permalink_context() + candidates = build_permalink_resolution_candidates( + data.note.file_path, + project.permalink, + include_project=app_config.permalinks_include_project, + workspace_permalink=( + workspace.workspace_slug if workspace and workspace.should_prefix_permalinks else None + ), + ) + try: + outcome = await note_content_mutation_service.write_note( + project_external_id=project_external_id, + data=data.note, + overwrite=data.overwrite, + entity_repository=entity_repository, + permalink_candidates=candidates, + user_profile_id=None, + source="api", + ) + except NoteContentMutationServiceError as error: + raise HTTPException(status_code=error.status_code, detail=error.detail) from error + match outcome: + case Created(change=change) | Updated(change=change): + accepted = await note_content_materialization_provider.materialize_write_change(change) + entity = EntityResponseV2.model_validate( + runtime_note_content_payload_as_dict(accepted.payload) + ) + # Runtime-injected schedulers preserve local and Cloud publication behavior. + if app_config.semantic_search_enabled: + vector_sync_scheduler.schedule_entity_vector_sync( + entity_id=entity.id, project_id=project_id + ) + relation_resolution_scheduler.schedule_relation_resolution(project_id=project_id) + match outcome: + case Created(): + return NoteCreated(entity=entity) + case Updated(): + return NoteUpdated(entity=entity) + case _: + assert_never(outcome) + case AlreadyExists(file_path=file_path): + return NoteAlreadyExists(file_path=file_path) + case TargetMoved(note=note): + return NoteTargetMoved(**asdict(note)) + case Locked(message=message): + return NoteLocked(message=message) + case Rejected(rejection=rejection): + error = note_content_mutation_error_from_rejection(rejection) + raise HTTPException(status_code=error.status_code, detail=error.detail) + case _: + assert_never(outcome) diff --git a/src/basic_memory/man/man3/write-note(3).md b/src/basic_memory/man/man3/write-note(3).md index 5bd9b77b0..b3f38a304 100644 --- a/src/basic_memory/man/man3/write-note(3).md +++ b/src/basic_memory/man/man3/write-note(3).md @@ -45,6 +45,13 @@ conflict error by default. Pass `overwrite=True` (CLI: `--overwrite`) to replace it. For incremental changes prefer [[edit-note(3)]], which appends, prepends, or edits sections in place without rewriting the file. +Overwrite addresses the exact file path generated from the title and directory. +If that path is vacant but its retained permalink identifies a moved note, +the tool returns `NOTE_PATH_CONFLICT` with the current path. Read or edit the +moved note by its identifier, or use `overwrite=False` to create a separate note. +If a replacement note already occupies the requested path, overwrite updates +that replacement. Locked notes refuse replacement without changing their content. + ## PARAMETERS - **title** (string, required) — The title of the note; written to frontmatter and drives the permalink. No H1 is added for you: content is saved as given, so include a "# Title" heading yourself if the note should open with one. diff --git a/src/basic_memory/mcp/clients/knowledge.py b/src/basic_memory/mcp/clients/knowledge.py index 45edac305..2a2b260bb 100644 --- a/src/basic_memory/mcp/clients/knowledge.py +++ b/src/basic_memory/mcp/clients/knowledge.py @@ -21,6 +21,12 @@ from basic_memory.schemas.v2.graph import GraphNode, OrphanEntitiesResponse from basic_memory.schemas.v2.entity import EntityResolveResponse, EntityResponseV2 from basic_memory.schemas.v2.accepted_content import AcceptedNoteContentBatchResponse +from basic_memory.schemas.base import Entity +from basic_memory.schemas.v2.note_write import ( + WriteNoteRequest, + WriteNoteResponse, + write_note_response_adapter, +) class KnowledgeClient: @@ -50,6 +56,20 @@ def __init__(self, http_client: AsyncClient, project_id: str): # --- Entity CRUD Operations --- + async def write_note(self, note: Entity, *, overwrite: bool) -> WriteNoteResponse: + """Write at an exact path and preserve the service's expected outcomes.""" + from basic_memory.mcp.tools.utils import call_post + + response = await call_post( + self.http_client, + f"{self._base_path}/write", + json=WriteNoteRequest(note=note, overwrite=overwrite).model_dump(mode="json"), + client_name="knowledge", + operation="write_note", + path_template="/v2/projects/{project_id}/knowledge/write", + ) + return write_note_response_adapter.validate_json(response.content) + async def create_entity(self, entity_data: dict[str, Any]) -> EntityResponse: """Create a new entity. diff --git a/src/basic_memory/mcp/tools/write_note.py b/src/basic_memory/mcp/tools/write_note.py index 92a1e3f8b..883c56b27 100644 --- a/src/basic_memory/mcp/tools/write_note.py +++ b/src/basic_memory/mcp/tools/write_note.py @@ -3,8 +3,7 @@ import dataclasses import textwrap from collections.abc import Sequence -from pathlib import Path -from typing import TYPE_CHECKING, Any, Annotated, List, Union, Optional, Literal +from typing import TYPE_CHECKING, Any, Annotated, List, Union, Optional, Literal, assert_never import logfire from httpx import HTTPStatusError @@ -18,6 +17,13 @@ from fastmcp import Context from fastmcp.exceptions import ToolError from basic_memory.schemas.base import Entity +from basic_memory.schemas.v2.note_write import ( + NoteCreated, + NoteUpdated, + NoteAlreadyExists, + NoteTargetMoved, + NoteLocked, +) from basic_memory.schemas.search import ( SearchItemType, SearchQuery, @@ -439,52 +445,45 @@ async def write_note( # Use typed KnowledgeClient for API calls knowledge_client = KnowledgeClient(client, active_project.external_id) - # Try to create the entity first (optimistic create) - logger.debug(f"Attempting to create entity permalink={entity.permalink}") - action = "Created" # Default to created - try: - result = await knowledge_client.create_entity(entity.model_dump()) - action = "Created" - except Exception as e: - # If creation failed due to conflict (already exists), try to update - if ( - "409" in str(e) - or "conflict" in str(e).lower() - or "already exists" in str(e).lower() - ): - # Guard: block overwrite unless explicitly enabled - if not effective_overwrite: - logger.warning( - f"write_note blocked: note already exists (overwrite not enabled) " - f"permalink={entity.permalink}" - ) - if output_format == "json": - return { - "title": title, - "permalink": entity.permalink, - "file_path": None, - "checksum": None, - "action": "conflict", - "error": "NOTE_ALREADY_EXISTS", - } - return _format_overwrite_error(title, entity.permalink, active_project.name) - - logger.debug(f"Entity exists, updating instead permalink={entity.permalink}") - # The create conflict identifies an existing file. Resolve its path - # strictly, then update by the returned UUID; no permalink is required. - # Fuzzy resolution could select a different note with a similar identity. - # POSIX-normalize so Windows clients send the same form the server stores. - file_path_identifier = Path(entity.file_path).as_posix() - entity_id = await knowledge_client.resolve_entity( - file_path_identifier, strict=True - ) - # Propagate the replacement failure (such as a locked-note refusal) - # instead of masking it with the initial create conflict. - result = await knowledge_client.update_entity(entity_id, entity.model_dump()) + # The API owns path identity and overwrite policy; expected outcomes stay + # typed all the way here, so presentation never has to parse an HTTP error. + outcome = await knowledge_client.write_note(entity, overwrite=effective_overwrite) + match outcome: + case NoteCreated(entity=result): + action = "Created" + case NoteUpdated(entity=result): action = "Updated" - else: - # Re-raise if it's not a conflict error - raise # pragma: no cover + case NoteAlreadyExists(): + if output_format == "json": + return { + "title": title, + "permalink": entity.permalink, + "file_path": None, + "checksum": None, + "action": "conflict", + "error": "NOTE_ALREADY_EXISTS", + } + return _format_overwrite_error(title, entity.permalink, active_project.name) + case NoteTargetMoved() as moved: + if output_format == "json": + return { + "title": moved.title, + "permalink": moved.permalink, + "file_path": moved.file_path, + "checksum": None, + "action": "conflict", + "error": "NOTE_PATH_CONFLICT", + } + return ( + "# Error: Note is at a different path\n\n" + f"The requested note is now at `{moved.file_path}`. " + f"Read or edit it using `{moved.external_id}`. " + "Use overwrite=False to create a separate note at the requested path." + ) + case NoteLocked(message=message): + raise ToolError(message) + case _: + assert_never(outcome) # --- Similar-note advisory --- # Trigger: the note was created (not updated). # Why: agents writing across sessions know the topic but not whether a note on @@ -550,7 +549,7 @@ async def write_note( f"project: {active_project.name}", f"file_path: {result.file_path}", f"permalink: {response_permalink}", - f"checksum: {result.checksum[:8] if result.checksum else 'unknown'}", + f"checksum: {result.file_checksum[:8] if result.file_checksum else 'unknown'}", ] # Count observations by category @@ -598,7 +597,7 @@ async def write_note( "title": result.title, "permalink": response_permalink, "file_path": result.file_path, - "checksum": result.checksum, + "checksum": result.file_checksum, "action": action.lower(), "similar_notes": [dataclasses.asdict(note) for note in similar_notes], } diff --git a/src/basic_memory/schemas/v2/note_write.py b/src/basic_memory/schemas/v2/note_write.py new file mode 100644 index 000000000..ae3d70d57 --- /dev/null +++ b/src/basic_memory/schemas/v2/note_write.py @@ -0,0 +1,49 @@ +"""Validated outcomes for the path-addressed note write operation.""" + +from typing import Annotated, Literal + +from pydantic import BaseModel, Field, TypeAdapter + +from basic_memory.schemas.base import Entity +from basic_memory.schemas.v2.entity import EntityResponseV2 + + +class WriteNoteRequest(BaseModel): + note: Entity + overwrite: bool = False + + +class NoteCreated(BaseModel): + kind: Literal["created"] = "created" + entity: EntityResponseV2 + + +class NoteUpdated(BaseModel): + kind: Literal["updated"] = "updated" + entity: EntityResponseV2 + + +class NoteAlreadyExists(BaseModel): + kind: Literal["already_exists"] = "already_exists" + file_path: str + + +class NoteTargetMoved(BaseModel): + kind: Literal["target_moved"] = "target_moved" + external_id: str + title: str + file_path: str + permalink: str | None + + +class NoteLocked(BaseModel): + kind: Literal["locked"] = "locked" + message: str + + +type WriteNoteResponse = Annotated[ + NoteCreated | NoteUpdated | NoteAlreadyExists | NoteTargetMoved | NoteLocked, + Field(discriminator="kind"), +] + +write_note_response_adapter = TypeAdapter(WriteNoteResponse) diff --git a/src/basic_memory/services/note_content_writes.py b/src/basic_memory/services/note_content_writes.py index a903f6f2f..79ca7d0e1 100644 --- a/src/basic_memory/services/note_content_writes.py +++ b/src/basic_memory/services/note_content_writes.py @@ -2,10 +2,10 @@ from __future__ import annotations -from collections.abc import AsyncIterator +from collections.abc import AsyncIterator, Sequence from contextlib import asynccontextmanager -from dataclasses import dataclass -from typing import Literal, Protocol +from dataclasses import dataclass, replace +from typing import Literal, Protocol, assert_never from uuid import UUID from loguru import logger @@ -24,6 +24,8 @@ AcceptedNoteMutationResult, AcceptedNoteUpdateMutation, load_existing_markdown_note_content, + load_accepted_note_mutation_project, + resolve_accepted_note_schema_directory, reject_stale_base_checksum, run_accepted_note_create, run_accepted_note_delete, @@ -45,6 +47,17 @@ ) from basic_memory.schemas.base import Entity as EntitySchema from basic_memory.schemas.request import EditEntityRequest +from basic_memory.repository.entity_repository import EntityRepository +from basic_memory.services.note_write_outcomes import ( + AlreadyExists, + Created, + Updated, + TargetMoved, + Locked, + Rejected, + NoteLocation, + WriteOutcome, +) AcceptedNoteChange = RuntimeAcceptedNoteChange[RuntimeNoteContentResponsePayload] @@ -332,6 +345,105 @@ async def freshen_existing_note_content( raise return True + async def write_note( + self, + *, + project_external_id: str, + data: EntitySchema, + overwrite: bool, + entity_repository: EntityRepository, + permalink_candidates: Sequence[str], + user_profile_id: UUID | None, + source: str, + ) -> WriteOutcome: + """Create at a path or replace its current owner, without search resolution. + + Retained exact permalinks only identify a moved target when the requested + path has no owner. Rejections leave the transaction before becoming values, + so the existing rollback, cache invalidation, and publication rules still apply. + """ + target: NoteLocation | None = None + try: + async with accepted_note_transaction(self.session_maker) as session: + project = await load_accepted_note_mutation_project( + session, + project_external_id=project_external_id, + dependencies=self.mutation_dependencies, + ) + if entity_repository.project_id != project.id: + raise ValueError("Write repository must belong to the requested project") + data = await resolve_accepted_note_schema_directory( + session, + project_id=project.id, + data=data, + dependencies=self.mutation_dependencies, + ) + existing = await entity_repository.get_by_file_path( + session, + data.file_path, + load_relations=False, + ) + if existing is not None: + if not overwrite: + return AlreadyExists(data.file_path) + target = NoteLocation( + str(existing.external_id), + existing.title, + existing.file_path, + existing.permalink, + ) + elif overwrite: + for permalink in permalink_candidates: + moved = await entity_repository.get_by_permalink( + session, + permalink, + load_relations=False, + ) + if moved is not None: + return TargetMoved( + NoteLocation( + str(moved.external_id), + moved.title, + moved.file_path, + moved.permalink, + ) + ) + + # Dispatch through the public operations so runtime overrides retain + # their pre-acceptance work as well as the in-transaction hook. + match target: + case None: + change = await self.create_note( + project_external_id=project_external_id, + data=data, + user_profile_id=user_profile_id, + source=source, + ) + return Created(change) + case NoteLocation(external_id=entity_id): + change = await self.update_note( + project_external_id=project_external_id, + entity_external_id=entity_id, + data=data, + user_profile_id=user_profile_id, + source=source, + ) + return Updated(change) + case _: + assert_never(target) + except AcceptedNoteMutationRejected as error: + return Rejected(error.rejection) + except NoteContentMutationServiceError as error: + # Legacy create/update adapters expose structured service errors. + # Translate their recoverable outcomes once; preserve other refusals. + match error.status_code: + case 423: + return Locked(str(error.detail)) + case 409 if target is None: + return AlreadyExists(data.file_path) + case _: + raise + async def create_note( self, *, @@ -343,39 +455,15 @@ async def create_note( actor_name: str | None = None, ) -> AcceptedNoteChange: """POST a new markdown note into accepted DB state.""" - actor_context = self._resolve_actor( - "create", - user_profile_id=user_profile_id, - source=source, - actor_kind=actor_kind, - actor_name=actor_name, - ) try: - async with self._mutation_cache_scope(project_external_id): - async with accepted_note_transaction(self.session_maker) as session: - result = await run_accepted_note_create( - session, - request=AcceptedNoteCreateMutation( - project_external_id=project_external_id, - data=data, - actor=accepted_note_mutation_actor( - user_profile_id=actor_context.user_profile_id, - actor_kind=actor_context.actor_kind, - actor_name=actor_context.actor_name, - ), - source=actor_context.source, - ), - dependencies=self.mutation_dependencies, - ) - await self.on_accepted_mutation( - session, - project_external_id=project_external_id, - change=result.change, - mutation_kind="create", - source=actor_context.source, - ) - accepted = await self._finish_mutation(result) - return accepted + return await self._accept_write( + AcceptedNoteCreateMutation( + project_external_id=project_external_id, + data=data, + actor=AcceptedNoteMutationActor(user_profile_id, actor_kind, actor_name), + source=source, + ) + ) except AcceptedNoteMutationRejected as error: raise note_content_mutation_error_from_rejection(error.rejection) from error @@ -400,51 +488,81 @@ async def update_note( (issue #1445). It stays optional so callers without a synced base still write. """ - actor_context = self._resolve_actor( - "update", - user_profile_id=user_profile_id, - source=source, - actor_kind=actor_kind, - actor_name=actor_name, - ) - freshening_may_have_published = False try: - freshening_may_have_published = await self.freshen_existing_note_content( - project_external_id=project_external_id, - entity_external_id=entity_external_id, + return await self._accept_write( + AcceptedNoteUpdateMutation( + project_external_id=project_external_id, + entity_external_id=entity_external_id, + data=data, + actor=AcceptedNoteMutationActor(user_profile_id, actor_kind, actor_name), + source=source, + base_checksum=base_checksum, + ) ) - async with self._mutation_cache_scope( - project_external_id, - invalidate_on_rejection=freshening_may_have_published, - ): - async with accepted_note_transaction(self.session_maker) as session: - result = await run_accepted_note_update( - session, - request=AcceptedNoteUpdateMutation( - project_external_id=project_external_id, - entity_external_id=entity_external_id, - data=data, - actor=accepted_note_mutation_actor( - user_profile_id=actor_context.user_profile_id, - actor_kind=actor_context.actor_kind, - actor_name=actor_context.actor_name, - ), - source=actor_context.source, - base_checksum=base_checksum, - ), - dependencies=self.mutation_dependencies, - ) - await self.on_accepted_mutation( - session, - project_external_id=project_external_id, - change=result.change, - mutation_kind="update", - source=actor_context.source, - ) - accepted = await self._finish_mutation(result) except AcceptedNoteMutationRejected as error: raise note_content_mutation_error_from_rejection(error.rejection) from error - return accepted + + async def _accept_write( + self, + request: AcceptedNoteCreateMutation | AcceptedNoteUpdateMutation, + ) -> AcceptedNoteChange: + """Share actor resolution, transaction ownership and publication for full writes.""" + kind: NoteContentMutationKind + match request: + case AcceptedNoteCreateMutation(): + kind = "create" + case AcceptedNoteUpdateMutation(): + kind = "update" + case _: + assert_never(request) + actor = self._resolve_actor( + kind, + user_profile_id=request.actor.user_profile_id, + source=request.source, + actor_kind=request.actor.kind, + actor_name=request.actor.name, + ) + request = replace( + request, + actor=AcceptedNoteMutationActor( + actor.user_profile_id, actor.actor_kind, actor.actor_name + ), + source=actor.source, + ) + freshened = False + if isinstance(request, AcceptedNoteUpdateMutation): + freshened = await self.freshen_existing_note_content( + project_external_id=request.project_external_id, + entity_external_id=request.entity_external_id, + ) + async with self._mutation_cache_scope( + request.project_external_id, + invalidate_on_rejection=freshened, + ): + async with accepted_note_transaction(self.session_maker) as session: + match request: + case AcceptedNoteCreateMutation(): + result = await run_accepted_note_create( + session, + request=request, + dependencies=self.mutation_dependencies, + ) + case AcceptedNoteUpdateMutation(): + result = await run_accepted_note_update( + session, + request=request, + dependencies=self.mutation_dependencies, + ) + case _: + assert_never(request) + await self.on_accepted_mutation( + session, + project_external_id=request.project_external_id, + change=result.change, + mutation_kind=kind, + source=actor.source, + ) + return await self._finish_mutation(result) async def edit_note( self, diff --git a/src/basic_memory/services/note_write_outcomes.py b/src/basic_memory/services/note_write_outcomes.py new file mode 100644 index 000000000..13555d593 --- /dev/null +++ b/src/basic_memory/services/note_write_outcomes.py @@ -0,0 +1,49 @@ +"""Expected outcomes of writing a note at a requested project path.""" + +from dataclasses import dataclass + +from basic_memory.indexing.accepted_note_mutation_runner import ( + AcceptedNoteMutationChange, + AcceptedNoteMutationRejection, +) + + +@dataclass(frozen=True, slots=True) +class NoteLocation: + external_id: str + title: str + file_path: str + permalink: str | None + + +@dataclass(frozen=True, slots=True) +class Created: + change: AcceptedNoteMutationChange + + +@dataclass(frozen=True, slots=True) +class Updated: + change: AcceptedNoteMutationChange + + +@dataclass(frozen=True, slots=True) +class AlreadyExists: + file_path: str + + +@dataclass(frozen=True, slots=True) +class TargetMoved: + note: NoteLocation + + +@dataclass(frozen=True, slots=True) +class Locked: + message: str + + +@dataclass(frozen=True, slots=True) +class Rejected: + rejection: AcceptedNoteMutationRejection + + +type WriteOutcome = Created | Updated | AlreadyExists | TargetMoved | Locked | Rejected diff --git a/test-int/mcp/test_moved_note_overwrite.py b/test-int/mcp/test_moved_note_overwrite.py new file mode 100644 index 000000000..e2245c68e --- /dev/null +++ b/test-int/mcp/test_moved_note_overwrite.py @@ -0,0 +1,92 @@ +"""An overwrite must not silently create a shadow of a renamed note.""" + +import json +from pathlib import Path + +import pytest +from fastmcp import Client +from basic_memory.config import ConfigManager + + +@pytest.mark.asyncio +@pytest.mark.parametrize("output_format", ["text", "json"]) +async def test_overwrite_after_rename_refuses_without_changing_files( + mcp_server, app, test_project, app_config, output_format +): + app_config.update_permalinks_on_move = False + ConfigManager().save_config(app_config) + async with Client(mcp_server) as client: + arguments = { + "project": test_project.name, + "title": "song-sketching", + "directory": "app/probe", + "content": "# original\nfirst body", + } + await client.call_tool("write_note", arguments) + await client.call_tool( + "move_note", + { + "project": test_project.name, + "identifier": "song-sketching", + "destination_path": "app/probe/SKILL.md", + }, + ) + moved = Path(test_project.path) / "app/probe/SKILL.md" + original = moved.read_bytes() + result = await client.call_tool( + "write_note", + { + **arguments, + "content": "# replacement\nsecond body", + "overwrite": True, + "output_format": output_format, + }, + ) + assert result.content[0].type == "text" + if output_format == "json": + payload = json.loads(result.content[0].text) + assert payload["action"] == "conflict" + assert payload["error"] == "NOTE_PATH_CONFLICT" + assert payload["file_path"] == "app/probe/SKILL.md" + else: + assert "different path" in result.content[0].text + assert "app/probe/SKILL.md" in result.content[0].text + assert moved.read_bytes() == original + assert sorted(path.name for path in moved.parent.glob("*.md")) == ["SKILL.md"] + + +@pytest.mark.asyncio +async def test_overwrite_prefers_replacement_at_exact_path( + mcp_server, app, test_project, app_config +): + app_config.update_permalinks_on_move = False + ConfigManager().save_config(app_config) + async with Client(mcp_server) as client: + arguments = { + "project": test_project.name, + "title": "song-sketching", + "directory": "app/probe", + "content": "Original moved body", + "output_format": "json", + } + await client.call_tool("write_note", arguments) + await client.call_tool( + "move_note", + { + "project": test_project.name, + "identifier": "song-sketching", + "destination_path": "app/probe/SKILL.md", + }, + ) + moved = Path(test_project.path) / "app/probe/SKILL.md" + original = moved.read_bytes() + await client.call_tool( + "write_note", {**arguments, "content": "Replacement", "overwrite": False} + ) + result = await client.call_tool( + "write_note", {**arguments, "content": "Updated replacement", "overwrite": True} + ) + assert result.content[0].type == "text" + assert json.loads(result.content[0].text)["action"] == "updated" + assert moved.read_bytes() == original + assert "Updated replacement" in (moved.parent / "song-sketching.md").read_text() diff --git a/test-int/mcp/test_write_note_integration.py b/test-int/mcp/test_write_note_integration.py index ad1a750b7..32f7afe2b 100644 --- a/test-int/mcp/test_write_note_integration.py +++ b/test-int/mcp/test_write_note_integration.py @@ -125,22 +125,10 @@ async def test_write_note_update_existing(mcp_server, app, test_project): @pytest.mark.asyncio -async def test_write_note_overwrite_resolves_conflict_by_file_path_when_permalink_changes( - mcp_server, app, test_project, monkeypatch +async def test_write_note_overwrite_preserves_path_when_permalink_changes( + mcp_server, app, test_project ): - """Overwrite resolves the conflict by strict file path through the MCP client stack.""" - from basic_memory.mcp.clients import knowledge as knowledge_mod - - original_resolve = knowledge_mod.KnowledgeClient.resolve_entity - captured_resolve: dict[str, Any] = {} - - async def spy_resolve(self, identifier: str, *, strict: bool = False) -> str: - captured_resolve["identifier"] = identifier - captured_resolve["strict"] = strict - return await original_resolve(self, identifier, strict=strict) - - monkeypatch.setattr(knowledge_mod.KnowledgeClient, "resolve_entity", spy_resolve) - + """A custom permalink replacement still updates the exact requested file.""" async with Client(mcp_server) as client: created = await client.call_tool( "write_note", @@ -182,10 +170,6 @@ async def spy_resolve(self, identifier: str, *, strict: bool = False) -> str: assert updated_payload["action"] == "updated" assert updated_payload["permalink"] == "overwrite-conflicts/custom-overwrite-permalink" assert updated_payload["file_path"] == "overwrite-conflicts/Overwrite Permalink Change.md" - assert captured_resolve == { - "identifier": "overwrite-conflicts/Overwrite Permalink Change.md", - "strict": True, - } read_updated = await client.call_tool( "read_note", diff --git a/test-int/test_note_write_outcomes.py b/test-int/test_note_write_outcomes.py new file mode 100644 index 000000000..99347d81c --- /dev/null +++ b/test-int/test_note_write_outcomes.py @@ -0,0 +1,134 @@ +"""Typed write outcomes preserve canonical content across the HTTP boundary.""" + +from pathlib import Path +from unittest.mock import AsyncMock + +import pytest +from httpx import AsyncClient +from sqlalchemy.ext.asyncio import AsyncSession + +from basic_memory.models import Project +from basic_memory.services.note_content_writes import ( + AcceptedNoteChange, + NoteContentMutationKind, + NoteContentMutationService, + NoteContentMutationServiceError, +) + + +async def test_write_outcomes_preserve_identity_and_content( + client: AsyncClient, + test_project: Project, +) -> None: + endpoint = f"/v2/projects/{test_project.external_id}/knowledge/write" + note = {"title": "Typed Write", "directory": "notes", "content": "Original"} + created = await client.post(endpoint, json={"note": note}) + assert created.status_code == 200 + assert created.json()["kind"] == "created" + entity_id = created.json()["entity"]["external_id"] + path = Path(test_project.path) / "notes/Typed Write.md" + original = path.read_bytes() + + exists = await client.post(endpoint, json={"note": {**note, "content": "Refused"}}) + assert exists.json() == {"kind": "already_exists", "file_path": "notes/Typed Write.md"} + assert path.read_bytes() == original + + updated = await client.post( + endpoint, json={"note": {**note, "content": "Replacement"}, "overwrite": True} + ) + assert updated.json()["kind"] == "updated" + assert updated.json()["entity"]["external_id"] == entity_id + assert "Replacement" in path.read_text() + + +async def test_write_rejection_keeps_validation_detail( + client: AsyncClient, + test_project: Project, +) -> None: + response = await client.post( + f"/v2/projects/{test_project.external_id}/knowledge/write", + json={ + "note": { + "title": "Invalid", + "directory": "notes", + "content": "{}", + "content_type": "application/json", + } + }, + ) + assert response.status_code == 415 + assert response.json()["detail"] == ( + "Only markdown note writes are supported by the note-content path." + ) + assert not (Path(test_project.path) / "notes/Invalid.md").exists() + + +@pytest.mark.parametrize("overwrite", [False, True]) +async def test_write_preserves_runtime_operation_overrides( + client: AsyncClient, + test_project: Project, + monkeypatch: pytest.MonkeyPatch, + overwrite: bool, +) -> None: + endpoint = f"/v2/projects/{test_project.external_id}/knowledge/write" + note = {"title": "Runtime Policy", "directory": "notes", "content": "Original"} + if overwrite: + response = await client.post(endpoint, json={"note": note}) + assert response.json()["kind"] == "created" + operation = "update_note" if overwrite else "create_note" + override = AsyncMock(side_effect=NoteContentMutationServiceError(429, "Runtime write limit")) + monkeypatch.setattr(NoteContentMutationService, operation, override) + response = await client.post(endpoint, json={"note": note, "overwrite": overwrite}) + assert response.status_code == 429 + assert response.json() == {"detail": "Runtime write limit"} + override.assert_awaited_once() + + +@pytest.mark.parametrize("overwrite", [False, True]) +async def test_write_hook_failure_rolls_back_canonical_acceptance( + client: AsyncClient, + test_project: Project, + monkeypatch: pytest.MonkeyPatch, + overwrite: bool, +) -> None: + endpoint = f"/v2/projects/{test_project.external_id}/knowledge/write" + note = {"title": "Hook", "directory": "notes", "content": "Original"} + path = Path(test_project.path) / "notes/Hook.md" + created = await client.post(endpoint, json={"note": note}) if overwrite else None + if created is not None: + assert created.json()["kind"] == "created" + original = path.read_bytes() if overwrite else None + + async def reject_hook( + self: NoteContentMutationService, + session: AsyncSession, + *, + project_external_id: str, + change: AcceptedNoteChange, + mutation_kind: NoteContentMutationKind, + source: str, + ) -> None: + assert session.in_transaction() + assert project_external_id == str(test_project.external_id) + assert mutation_kind == ("update" if overwrite else "create") + assert source == "api" + raise RuntimeError("Runtime marker failed") + + monkeypatch.setattr(NoteContentMutationService, "on_accepted_mutation", reject_hook) + with pytest.raises(RuntimeError, match="Runtime marker failed"): + await client.post( + endpoint, json={"note": {**note, "content": "Refused"}, "overwrite": overwrite} + ) + if created is not None: + assert path.read_bytes() == original + result = await client.get( + f"/v2/projects/{test_project.external_id}/knowledge/entities/" + f"{created.json()['entity']['external_id']}" + ) + assert "Original" in result.json()["content"] + assert "Refused" not in result.json()["content"] + else: + assert not path.exists() + monkeypatch.undo() + retried = await client.post(endpoint, json={"note": note}) + assert retried.json()["kind"] == "created" diff --git a/tests/mcp/test_tool_write_note.py b/tests/mcp/test_tool_write_note.py index d4f60f988..4c6fb9921 100644 --- a/tests/mcp/test_tool_write_note.py +++ b/tests/mcp/test_tool_write_note.py @@ -1481,37 +1481,10 @@ async def test_write_note_new_note_unaffected(self, app, test_project): assert "file_path: guard/Brand New Note.md" in result @pytest.mark.asyncio - async def test_write_note_overwrite_resolves_by_file_path_strictly( - self, app, test_project, entity_repository, session_maker, monkeypatch + async def test_write_note_overwrite_preserves_exact_path_identity( + self, app, test_project, entity_repository, session_maker ): - """Regression: overwrite=True must resolve the conflicting entity by - file_path with strict=True, not by permalink with fuzzy fallback. - - Bug shape: in workspace-prefixed palaces the client-built permalink - omits the workspace slug, so resolve_entity(permalink) with the default - strict=False would fall through to fuzzy search and could pick an - orphan row sharing tokens with the canonical permalink. The update - then wrote to the orphan, the canonical row stayed stale, and the - next overwrite minted a -1/-2 suffix because the permalink uniqueness - check found duplicate rows. - - The 409 we catch came from a file_service.exists(file_path) check, - so file_path is the authoritative key — strict resolution against it - is safe even when permalinks are workspace-prefixed elsewhere. - """ - # Spy on the resolve_entity call to assert the identifier and strict flag. - from basic_memory.mcp.clients import knowledge as knowledge_mod - - original_resolve = knowledge_mod.KnowledgeClient.resolve_entity - captured: dict[str, Any] = {} - - async def spy_resolve(self, identifier, *, strict=False): - captured["identifier"] = identifier - captured["strict"] = strict - return await original_resolve(self, identifier, strict=strict) - - monkeypatch.setattr(knowledge_mod.KnowledgeClient, "resolve_entity", spy_resolve) - + """Replacing an exact path preserves its UUID and does not mint duplicate identities.""" # Create then overwrite the canonical note. await write_note( project=test_project.name, @@ -1534,11 +1507,6 @@ async def spy_resolve(self, identifier, *, strict=False): ) assert "# Updated note" in result - # The overwrite path resolved by file_path with strict=True — not by - # permalink with the default fuzzy fallback. - assert captured.get("identifier") == "features/foo/Overview.md" - assert captured.get("strict") is True - # And the canonical row was updated in place — no duplicate -1/-2 row. async with db.scoped_session(session_maker) as session: canonical_after = await entity_repository.get_by_permalink(session, canonical_permalink) From 1b02c1ceb7719e39e9a292bac3aa413817ff7968 Mon Sep 17 00:00:00 2001 From: phernandez Date: Tue, 8 Sep 2026 10:07:18 -0500 Subject: [PATCH 4/5] fix(mcp): preserve supplied identity when detecting moved notes Signed-off-by: phernandez --- .../services/note_content_writes.py | 11 ++++++++++ test-int/mcp/test_moved_note_overwrite.py | 8 +++++--- test-int/test_note_write_outcomes.py | 20 +++++++++++++++++++ 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/src/basic_memory/services/note_content_writes.py b/src/basic_memory/services/note_content_writes.py index 79ca7d0e1..1d297afec 100644 --- a/src/basic_memory/services/note_content_writes.py +++ b/src/basic_memory/services/note_content_writes.py @@ -11,6 +11,8 @@ from loguru import logger from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker +from basic_memory.file_utils import ParseError, has_frontmatter, parse_frontmatter + from basic_memory.indexing.accepted_note_mutation_runner import ( AcceptedNoteCreateMutation, AcceptedNoteDeleteMutation, @@ -393,6 +395,13 @@ async def write_note( existing.permalink, ) elif overwrite: + # A supplied frontmatter permalink is the identity preparation + # would use. Check it before generated path aliases to avoid + # creating a suffixed shadow of a moved custom-permalink note. + if data.content and has_frontmatter(data.content): + permalink = parse_frontmatter(data.content).get("permalink") + if isinstance(permalink, str) and permalink: + permalink_candidates = (permalink, *permalink_candidates) for permalink in permalink_candidates: moved = await entity_repository.get_by_permalink( session, @@ -433,6 +442,8 @@ async def write_note( assert_never(target) except AcceptedNoteMutationRejected as error: return Rejected(error.rejection) + except ParseError as error: + raise NoteContentMutationServiceError(400, str(error)) from error except NoteContentMutationServiceError as error: # Legacy create/update adapters expose structured service errors. # Translate their recoverable outcomes once; preserve other refusals. diff --git a/test-int/mcp/test_moved_note_overwrite.py b/test-int/mcp/test_moved_note_overwrite.py index e2245c68e..447e17e06 100644 --- a/test-int/mcp/test_moved_note_overwrite.py +++ b/test-int/mcp/test_moved_note_overwrite.py @@ -10,17 +10,19 @@ @pytest.mark.asyncio @pytest.mark.parametrize("output_format", ["text", "json"]) +@pytest.mark.parametrize("custom_permalink", [None, "custom/song"]) async def test_overwrite_after_rename_refuses_without_changing_files( - mcp_server, app, test_project, app_config, output_format + mcp_server, app, test_project, app_config, output_format, custom_permalink ): app_config.update_permalinks_on_move = False ConfigManager().save_config(app_config) + frontmatter = f"---\npermalink: {custom_permalink}\n---\n" if custom_permalink else "" async with Client(mcp_server) as client: arguments = { "project": test_project.name, "title": "song-sketching", "directory": "app/probe", - "content": "# original\nfirst body", + "content": f"{frontmatter}# original\nfirst body", } await client.call_tool("write_note", arguments) await client.call_tool( @@ -37,7 +39,7 @@ async def test_overwrite_after_rename_refuses_without_changing_files( "write_note", { **arguments, - "content": "# replacement\nsecond body", + "content": f"{frontmatter}# replacement\nsecond body", "overwrite": True, "output_format": output_format, }, diff --git a/test-int/test_note_write_outcomes.py b/test-int/test_note_write_outcomes.py index 99347d81c..df2c5caff 100644 --- a/test-int/test_note_write_outcomes.py +++ b/test-int/test_note_write_outcomes.py @@ -63,6 +63,26 @@ async def test_write_rejection_keeps_validation_detail( assert not (Path(test_project.path) / "notes/Invalid.md").exists() +async def test_write_rejects_invalid_frontmatter_before_selecting_identity( + client: AsyncClient, + test_project: Project, +) -> None: + response = await client.post( + f"/v2/projects/{test_project.external_id}/knowledge/write", + json={ + "note": { + "title": "Invalid", + "directory": "notes", + "content": "---\npermalink: [broken\n---\nBody", + }, + "overwrite": True, + }, + ) + assert response.status_code == 400 + assert "Invalid YAML" in response.json()["detail"] + assert not (Path(test_project.path) / "notes/Invalid.md").exists() + + @pytest.mark.parametrize("overwrite", [False, True]) async def test_write_preserves_runtime_operation_overrides( client: AsyncClient, From dbcc2975beae3a9489a476db3d1b36bcb43c5793 Mon Sep 17 00:00:00 2001 From: phernandez Date: Tue, 8 Sep 2026 10:25:49 -0500 Subject: [PATCH 5/5] fix(mcp): retain tracing for typed write operations Signed-off-by: phernandez --- .../api/v2/routers/note_write_router.py | 117 ++++++++++-------- src/basic_memory/mcp/clients/knowledge.py | 17 ++- tests/mcp/test_tool_telemetry.py | 7 +- 3 files changed, 81 insertions(+), 60 deletions(-) diff --git a/src/basic_memory/api/v2/routers/note_write_router.py b/src/basic_memory/api/v2/routers/note_write_router.py index 9dfdb3c4e..020a72da4 100644 --- a/src/basic_memory/api/v2/routers/note_write_router.py +++ b/src/basic_memory/api/v2/routers/note_write_router.py @@ -3,6 +3,7 @@ from dataclasses import asdict from typing import Annotated, assert_never +import logfire from fastapi import APIRouter, HTTPException, Path from basic_memory.deps import ( @@ -60,59 +61,69 @@ async def write_note( app_config: AppConfigDep, ) -> WriteNoteResponse: """Create at the requested path or replace the note that currently owns it.""" - # Release the read connection before the mutation opens its own transaction. - async with session_maker() as session: - project = await project_repository.get_by_id(session, project_id) - if project is None: - raise HTTPException(status_code=404, detail="Project not found") - workspace = current_workspace_permalink_context() - candidates = build_permalink_resolution_candidates( - data.note.file_path, - project.permalink, - include_project=app_config.permalinks_include_project, - workspace_permalink=( - workspace.workspace_slug if workspace and workspace.should_prefix_permalinks else None - ), - ) - try: - outcome = await note_content_mutation_service.write_note( - project_external_id=project_external_id, - data=data.note, - overwrite=data.overwrite, - entity_repository=entity_repository, - permalink_candidates=candidates, - user_profile_id=None, - source="api", + with logfire.span( + "api.request.knowledge.write_note", + entrypoint="api", + domain="knowledge", + action="write_note", + ): + # Release the read connection before the mutation opens its own transaction. + async with session_maker() as session: + project = await project_repository.get_by_id(session, project_id) + if project is None: + raise HTTPException(status_code=404, detail="Project not found") + workspace = current_workspace_permalink_context() + candidates = build_permalink_resolution_candidates( + data.note.file_path, + project.permalink, + include_project=app_config.permalinks_include_project, + workspace_permalink=( + workspace.workspace_slug + if workspace and workspace.should_prefix_permalinks + else None + ), ) - except NoteContentMutationServiceError as error: - raise HTTPException(status_code=error.status_code, detail=error.detail) from error - match outcome: - case Created(change=change) | Updated(change=change): - accepted = await note_content_materialization_provider.materialize_write_change(change) - entity = EntityResponseV2.model_validate( - runtime_note_content_payload_as_dict(accepted.payload) + try: + outcome = await note_content_mutation_service.write_note( + project_external_id=project_external_id, + data=data.note, + overwrite=data.overwrite, + entity_repository=entity_repository, + permalink_candidates=candidates, + user_profile_id=None, + source="api", ) - # Runtime-injected schedulers preserve local and Cloud publication behavior. - if app_config.semantic_search_enabled: - vector_sync_scheduler.schedule_entity_vector_sync( - entity_id=entity.id, project_id=project_id + except NoteContentMutationServiceError as error: + raise HTTPException(status_code=error.status_code, detail=error.detail) from error + match outcome: + case Created(change=change) | Updated(change=change): + accepted = await note_content_materialization_provider.materialize_write_change( + change ) - relation_resolution_scheduler.schedule_relation_resolution(project_id=project_id) - match outcome: - case Created(): - return NoteCreated(entity=entity) - case Updated(): - return NoteUpdated(entity=entity) - case _: - assert_never(outcome) - case AlreadyExists(file_path=file_path): - return NoteAlreadyExists(file_path=file_path) - case TargetMoved(note=note): - return NoteTargetMoved(**asdict(note)) - case Locked(message=message): - return NoteLocked(message=message) - case Rejected(rejection=rejection): - error = note_content_mutation_error_from_rejection(rejection) - raise HTTPException(status_code=error.status_code, detail=error.detail) - case _: - assert_never(outcome) + entity = EntityResponseV2.model_validate( + runtime_note_content_payload_as_dict(accepted.payload) + ) + # Runtime-injected schedulers preserve local and Cloud publication behavior. + if app_config.semantic_search_enabled: + vector_sync_scheduler.schedule_entity_vector_sync( + entity_id=entity.id, project_id=project_id + ) + relation_resolution_scheduler.schedule_relation_resolution(project_id=project_id) + match outcome: + case Created(): + return NoteCreated(entity=entity) + case Updated(): + return NoteUpdated(entity=entity) + case _: + assert_never(outcome) + case AlreadyExists(file_path=file_path): + return NoteAlreadyExists(file_path=file_path) + case TargetMoved(note=note): + return NoteTargetMoved(**asdict(note)) + case Locked(message=message): + return NoteLocked(message=message) + case Rejected(rejection=rejection): + error = note_content_mutation_error_from_rejection(rejection) + raise HTTPException(status_code=error.status_code, detail=error.detail) + case _: + assert_never(outcome) diff --git a/src/basic_memory/mcp/clients/knowledge.py b/src/basic_memory/mcp/clients/knowledge.py index 2a2b260bb..57b868c2c 100644 --- a/src/basic_memory/mcp/clients/knowledge.py +++ b/src/basic_memory/mcp/clients/knowledge.py @@ -60,14 +60,19 @@ async def write_note(self, note: Entity, *, overwrite: bool) -> WriteNoteRespons """Write at an exact path and preserve the service's expected outcomes.""" from basic_memory.mcp.tools.utils import call_post - response = await call_post( - self.http_client, - f"{self._base_path}/write", - json=WriteNoteRequest(note=note, overwrite=overwrite).model_dump(mode="json"), + with logfire.span( + "mcp.client.knowledge.write_note", client_name="knowledge", operation="write_note", - path_template="/v2/projects/{project_id}/knowledge/write", - ) + ): + response = await call_post( + self.http_client, + f"{self._base_path}/write", + json=WriteNoteRequest(note=note, overwrite=overwrite).model_dump(mode="json"), + client_name="knowledge", + operation="write_note", + path_template="/v2/projects/{project_id}/knowledge/write", + ) return write_note_response_adapter.validate_json(response.content) async def create_entity(self, entity_data: dict[str, Any]) -> EntityResponse: diff --git a/tests/mcp/test_tool_telemetry.py b/tests/mcp/test_tool_telemetry.py index 6338c5dce..f75bfe9d3 100644 --- a/tests/mcp/test_tool_telemetry.py +++ b/tests/mcp/test_tool_telemetry.py @@ -73,7 +73,12 @@ async def test_write_note_emits_root_operation_and_project_context( }, ) span_names = [name for name, _ in spans] - assert "api.request.knowledge.create_entity" in span_names + assert "mcp.client.knowledge.write_note" in span_names + assert _contains_span_attrs( + spans, + "api.request.knowledge.write_note", + {"entrypoint": "api", "domain": "knowledge", "action": "write_note"}, + ) assert _contains_span_attrs( spans, "routing.client_session",