diff --git a/src/basic_memory/importers/base.py b/src/basic_memory/importers/base.py index 7f4170d05..9de502cca 100644 --- a/src/basic_memory/importers/base.py +++ b/src/basic_memory/importers/base.py @@ -2,6 +2,8 @@ import logging from abc import abstractmethod +from collections import Counter +from collections.abc import Sequence from contextlib import nullcontext from dataclasses import dataclass from pathlib import Path @@ -123,6 +125,69 @@ def build_import_paths(self, path: str) -> tuple[str, str]: permalink = self.canonical_permalink(path) return permalink, f"{path}.md" + def resolve_unique_import_paths( + self, + path: str, + seen_paths: set[str], + disambiguator: str | None = None, + *, + prefer_disambiguator: bool = False, + ) -> tuple[str, str]: + """Return a (permalink, file_path) that does not collide with seen_paths.""" + if prefer_disambiguator and disambiguator: + candidates = [f"{path}-{disambiguator}"] + else: + candidates = [path] + if disambiguator: + candidates.append(f"{path}-{disambiguator}") + + for candidate in candidates: + permalink, file_path = self.build_import_paths(candidate) + key = file_path.casefold() + if key not in seen_paths: + seen_paths.add(key) + return permalink, file_path + + base = f"{path}-{disambiguator}" if disambiguator else path + suffix = 2 + while True: + permalink, file_path = self.build_import_paths(f"{base}-{suffix}") + key = file_path.casefold() + if key not in seen_paths: + seen_paths.add(key) + return permalink, file_path + suffix += 1 + + def plan_unique_import_paths( + self, + entries: Sequence[tuple[str, str | None]], + ) -> list[tuple[str, str]]: + """Plan collision-free import paths without depending on batch order.""" + base_paths = [self.build_import_paths(path) for path, _ in entries] + base_counts = Counter(file_path.casefold() for _, file_path in base_paths) + seen_paths: set[str] = set() + planned: list[tuple[str, str] | None] = [None] * len(entries) + + # Reserve unique base paths first so colliding entries do not claim them. + for idx, ((_, _), (permalink, file_path)) in enumerate( + zip(entries, base_paths, strict=True) + ): + key = file_path.casefold() + if base_counts[key] == 1: + seen_paths.add(key) + planned[idx] = (permalink, file_path) + + for idx, (path, disambiguator) in enumerate(entries): + if planned[idx] is None: + planned[idx] = self.resolve_unique_import_paths( + path, + seen_paths, + disambiguator=disambiguator, + prefer_disambiguator=True, + ) + + return [item for item in planned if item is not None] + async def ensure_folder_exists(self, folder: str) -> None: """Ensure folder exists using FileService. diff --git a/src/basic_memory/importers/chatgpt_importer.py b/src/basic_memory/importers/chatgpt_importer.py index bb03574b3..5d45f828b 100644 --- a/src/basic_memory/importers/chatgpt_importer.py +++ b/src/basic_memory/importers/chatgpt_importer.py @@ -53,11 +53,8 @@ async def import_data( await self.ensure_folder_exists(destination_folder) conversations = source_data - # Process each conversation - messages_imported = 0 - chats_imported = 0 - file_paths: list[str] = [] - + # Prepare metadata and resolve unique, order-independent paths + prepared: list[tuple[dict[str, Any], float, float, str, str, str | None]] = [] for chat in conversations: created_at, modified_at = self._resolve_timestamps(chat) date_prefix = datetime.fromtimestamp(created_at).astimezone().strftime("%Y%m%d") @@ -68,8 +65,27 @@ async def import_data( if destination_folder else f"{date_prefix}-{clean_title}" ) - permalink, file_path = self.build_import_paths(relative_path) + stable_id = self._stable_id(chat) + disambiguator = clean_filename(stable_id)[:32] if stable_id else None + prepared.append( + (chat, created_at, modified_at, title, relative_path, disambiguator) + ) + + planned_paths = self.plan_unique_import_paths( + [ + (relative_path, disambiguator) + for _, _, _, _, relative_path, disambiguator in prepared + ] + ) + + # Process each conversation + messages_imported = 0 + chats_imported = 0 + file_paths: list[str] = [] + for (chat, created_at, modified_at, title, _, _), (permalink, file_path) in zip( + prepared, planned_paths, strict=True + ): # Convert to entity entity = self._format_chat_content(chat, title, permalink, created_at, modified_at) @@ -161,17 +177,21 @@ def _resolve_title(self, conversation: Dict[str, Any]) -> str: title = conversation.get("title") if isinstance(title, str) and title.strip(): return title - stable_id = ( - conversation.get("conversation_id") - or conversation.get("id") - or self._root_message_id(conversation) - ) + stable_id = self._stable_id(conversation) if not stable_id: raise ValueError( "ChatGPT conversation has no title, conversation id, or root message id" ) return f"Untitled conversation {stable_id}" + def _stable_id(self, conversation: Dict[str, Any]) -> str | None: + """Return a stable export identifier for fallback titles and disambiguation.""" + return ( + conversation.get("conversation_id") + or conversation.get("id") + or self._root_message_id(conversation) + ) + def _root_message_id(self, conversation: Dict[str, Any]) -> str | None: """The id of the conversation's root node, which later messages never change.""" for node_id, node in conversation.get("mapping", {}).items(): diff --git a/src/basic_memory/importers/claude_conversations_importer.py b/src/basic_memory/importers/claude_conversations_importer.py index f1366b443..14f9f630a 100644 --- a/src/basic_memory/importers/claude_conversations_importer.py +++ b/src/basic_memory/importers/claude_conversations_importer.py @@ -49,11 +49,8 @@ async def import_data( conversations = source_data - # Process each conversation - messages_imported = 0 - chats_imported = 0 - file_paths: list[str] = [] - + # Prepare metadata and resolve unique, order-independent paths + prepared: list[tuple[dict[str, Any], str, str, str | None]] = [] for chat in conversations: # Get name, providing default for unnamed conversations chat_name = chat.get("name") or f"Conversation {chat.get('uuid', 'untitled')}" @@ -66,8 +63,21 @@ async def import_data( if destination_folder else f"{date_prefix}-{clean_title}" ) - permalink, file_path = self.build_import_paths(relative_path) + disambiguator = clean_filename(chat["uuid"])[:32] if chat.get("uuid") else None + prepared.append((chat, chat_name, relative_path, disambiguator)) + + planned_paths = self.plan_unique_import_paths( + [(relative_path, disambiguator) for _, _, relative_path, disambiguator in prepared] + ) + + # Process each conversation + messages_imported = 0 + chats_imported = 0 + file_paths: list[str] = [] + for (chat, chat_name, _, _), (permalink, file_path) in zip( + prepared, planned_paths, strict=True + ): # Convert to entity entity = self._format_chat_content( name=chat_name, diff --git a/tests/importers/test_conversation_filename_collisions.py b/tests/importers/test_conversation_filename_collisions.py new file mode 100644 index 000000000..570210215 --- /dev/null +++ b/tests/importers/test_conversation_filename_collisions.py @@ -0,0 +1,179 @@ +"""Regression tests preventing filename collisions across conversation imports.""" + +from pathlib import Path + +import pytest + +from basic_memory.importers.chatgpt_importer import ChatGPTImporter +from basic_memory.importers.claude_conversations_importer import ClaudeConversationsImporter +from basic_memory.markdown.entity_parser import EntityParser +from basic_memory.markdown.markdown_processor import MarkdownProcessor +from basic_memory.services.file_service import FileService + + +def _chatgpt_conversation(cid: str | None, title: str | None, text: str) -> dict: + chat: dict = { + "create_time": 1760000000, + "mapping": { + "root": { + "id": "root", + "parent": None, + "children": ["msg-1"], + "message": None, + }, + "msg-1": { + "id": "msg-1", + "parent": "root", + "children": [], + "message": { + "id": "msg-1", + "author": {"role": "user"}, + "create_time": 1760000000, + "content": {"content_type": "text", "parts": [text]}, + }, + }, + }, + } + if cid is not None: + chat["id"] = cid + if title is not None: + chat["title"] = title + return chat + + +def _setup_services(tmp_path: Path) -> tuple[MarkdownProcessor, FileService]: + parser = EntityParser(base_path=tmp_path) + processor = MarkdownProcessor(entity_parser=parser) + files = FileService(base_path=tmp_path, markdown_processor=processor) + return processor, files + + +@pytest.mark.asyncio +async def test_chatgpt_import_disambiguates_untitled_and_titled_collision(tmp_path: Path): + """An untitled fallback and a matching explicit title must not overwrite each other.""" + processor, files = _setup_services(tmp_path) + importer = ChatGPTImporter(tmp_path, processor, files) + + conversations = [ + _chatgpt_conversation("abc", None, "FIRST_CONVERSATION"), + _chatgpt_conversation("other", "Untitled conversation abc", "SECOND_CONVERSATION"), + ] + result = await importer.import_data(conversations, "import") + + assert result.success + assert result.conversations == 2 + assert len(result.file_paths) == 2 + assert len(set(result.file_paths)) == 2 + + contents = [(tmp_path / p).read_text(encoding="utf-8") for p in result.file_paths] + assert any("FIRST_CONVERSATION" in c for c in contents) + assert any("SECOND_CONVERSATION" in c for c in contents) + + # Re-importing the same export preserves deterministic filenames instead of multiplying files. + second = await importer.import_data(conversations, "import") + assert second.file_paths == result.file_paths + + # Re-importing in reversed order preserves the same conversation-to-path mapping. + reversed_tmp = tmp_path / "reversed" + reversed_tmp.mkdir() + rev_processor, rev_files = _setup_services(reversed_tmp) + rev_importer = ChatGPTImporter(reversed_tmp, rev_processor, rev_files) + reversed_result = await rev_importer.import_data(list(reversed(conversations)), "import") + assert reversed_result.success + assert reversed_result.file_paths == list(reversed(result.file_paths)) + + +def test_plan_unique_import_paths_colliding_disambiguator_never_steals_unique_note(tmp_path: Path): + """A unique entry matching a disambiguated collision path keeps its path in any input order.""" + processor, files = _setup_services(tmp_path) + importer = ChatGPTImporter(tmp_path, processor, files) + + entries = [ + ("import/note", "abc"), + ("import/note", "other"), + ("import/note-abc", "third"), + ] + forward = importer.plan_unique_import_paths(entries) + assert [path for _, path in forward] == [ + "import/note-abc-2.md", + "import/note-other.md", + "import/note-abc.md", + ] + assert importer.plan_unique_import_paths(list(reversed(entries))) == list(reversed(forward)) + + +@pytest.mark.asyncio +async def test_chatgpt_import_disambiguates_normalized_and_case_collisions(tmp_path: Path): + """Distinct titles collapsing under clean_filename or case folding stay separate.""" + processor, files = _setup_services(tmp_path) + importer = ChatGPTImporter(tmp_path, processor, files) + + conversations = [ + _chatgpt_conversation(None, "Foo / Bar", "SLASH_CONTENT"), + _chatgpt_conversation(None, "Foo: Bar", "COLON_CONTENT"), + _chatgpt_conversation(None, "foo bar", "LOWER_CONTENT"), + ] + result = await importer.import_data(conversations, "import") + + assert result.success + assert result.conversations == 3 + assert len({p.casefold() for p in result.file_paths}) == 3 + + contents = [(tmp_path / p).read_text(encoding="utf-8") for p in result.file_paths] + assert any("SLASH_CONTENT" in c for c in contents) + assert any("COLON_CONTENT" in c for c in contents) + assert any("LOWER_CONTENT" in c for c in contents) + + +@pytest.mark.asyncio +async def test_claude_conversations_import_disambiguates_colliding_names(tmp_path: Path): + """Colliding Claude conversation filenames stay distinct instead of overwriting.""" + processor, files = _setup_services(tmp_path) + importer = ClaudeConversationsImporter(tmp_path, processor, files) + + def _msg(text: str) -> list[dict]: + return [ + { + "uuid": "m1", + "sender": "human", + "created_at": "2025-01-15T10:00:00Z", + "text": text, + "content": [{"type": "text", "text": text}], + "attachments": [], + } + ] + + conversations = [ + { + "uuid": "abc", + "name": "", + "created_at": "2025-01-15T10:00:00Z", + "updated_at": "2025-01-15T10:05:00Z", + "chat_messages": _msg("FIRST_CLAUDE"), + }, + { + "uuid": "other", + "name": "Conversation abc", + "created_at": "2025-01-15T10:10:00Z", + "updated_at": "2025-01-15T10:15:00Z", + "chat_messages": _msg("SECOND_CLAUDE"), + }, + ] + + result = await importer.import_data(conversations, "claude") + assert result.success + assert result.conversations == 2 + assert len(set(result.file_paths)) == 2 + + contents = [(tmp_path / p).read_text(encoding="utf-8") for p in result.file_paths] + assert any("FIRST_CLAUDE" in c for c in contents) + assert any("SECOND_CLAUDE" in c for c in contents) + + # Re-importing in reversed order keeps each conversation on the same output path. + reversed_tmp = tmp_path / "reversed_claude" + reversed_tmp.mkdir() + rev_processor, rev_files = _setup_services(reversed_tmp) + rev_importer = ClaudeConversationsImporter(reversed_tmp, rev_processor, rev_files) + reversed_result = await rev_importer.import_data(list(reversed(conversations)), "claude") + assert reversed_result.success + assert reversed_result.file_paths == list(reversed(result.file_paths))