basic-memory 0.17.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. basic_memory/__init__.py +7 -0
  2. basic_memory/alembic/alembic.ini +119 -0
  3. basic_memory/alembic/env.py +185 -0
  4. basic_memory/alembic/migrations.py +24 -0
  5. basic_memory/alembic/script.py.mako +26 -0
  6. basic_memory/alembic/versions/314f1ea54dc4_add_postgres_full_text_search_support_.py +131 -0
  7. basic_memory/alembic/versions/3dae7c7b1564_initial_schema.py +93 -0
  8. basic_memory/alembic/versions/502b60eaa905_remove_required_from_entity_permalink.py +51 -0
  9. basic_memory/alembic/versions/5fe1ab1ccebe_add_projects_table.py +120 -0
  10. basic_memory/alembic/versions/647e7a75e2cd_project_constraint_fix.py +112 -0
  11. basic_memory/alembic/versions/9d9c1cb7d8f5_add_mtime_and_size_columns_to_entity_.py +49 -0
  12. basic_memory/alembic/versions/a1b2c3d4e5f6_fix_project_foreign_keys.py +49 -0
  13. basic_memory/alembic/versions/a2b3c4d5e6f7_add_search_index_entity_cascade.py +56 -0
  14. basic_memory/alembic/versions/b3c3938bacdb_relation_to_name_unique_index.py +44 -0
  15. basic_memory/alembic/versions/cc7172b46608_update_search_index_schema.py +113 -0
  16. basic_memory/alembic/versions/e7e1f4367280_add_scan_watermark_tracking_to_project.py +37 -0
  17. basic_memory/alembic/versions/f8a9b2c3d4e5_add_pg_trgm_for_fuzzy_link_resolution.py +239 -0
  18. basic_memory/api/__init__.py +5 -0
  19. basic_memory/api/app.py +131 -0
  20. basic_memory/api/routers/__init__.py +11 -0
  21. basic_memory/api/routers/directory_router.py +84 -0
  22. basic_memory/api/routers/importer_router.py +152 -0
  23. basic_memory/api/routers/knowledge_router.py +318 -0
  24. basic_memory/api/routers/management_router.py +80 -0
  25. basic_memory/api/routers/memory_router.py +90 -0
  26. basic_memory/api/routers/project_router.py +448 -0
  27. basic_memory/api/routers/prompt_router.py +260 -0
  28. basic_memory/api/routers/resource_router.py +249 -0
  29. basic_memory/api/routers/search_router.py +36 -0
  30. basic_memory/api/routers/utils.py +169 -0
  31. basic_memory/api/template_loader.py +292 -0
  32. basic_memory/api/v2/__init__.py +35 -0
  33. basic_memory/api/v2/routers/__init__.py +21 -0
  34. basic_memory/api/v2/routers/directory_router.py +93 -0
  35. basic_memory/api/v2/routers/importer_router.py +182 -0
  36. basic_memory/api/v2/routers/knowledge_router.py +413 -0
  37. basic_memory/api/v2/routers/memory_router.py +130 -0
  38. basic_memory/api/v2/routers/project_router.py +342 -0
  39. basic_memory/api/v2/routers/prompt_router.py +270 -0
  40. basic_memory/api/v2/routers/resource_router.py +286 -0
  41. basic_memory/api/v2/routers/search_router.py +73 -0
  42. basic_memory/cli/__init__.py +1 -0
  43. basic_memory/cli/app.py +84 -0
  44. basic_memory/cli/auth.py +277 -0
  45. basic_memory/cli/commands/__init__.py +18 -0
  46. basic_memory/cli/commands/cloud/__init__.py +6 -0
  47. basic_memory/cli/commands/cloud/api_client.py +112 -0
  48. basic_memory/cli/commands/cloud/bisync_commands.py +110 -0
  49. basic_memory/cli/commands/cloud/cloud_utils.py +101 -0
  50. basic_memory/cli/commands/cloud/core_commands.py +195 -0
  51. basic_memory/cli/commands/cloud/rclone_commands.py +371 -0
  52. basic_memory/cli/commands/cloud/rclone_config.py +110 -0
  53. basic_memory/cli/commands/cloud/rclone_installer.py +263 -0
  54. basic_memory/cli/commands/cloud/upload.py +233 -0
  55. basic_memory/cli/commands/cloud/upload_command.py +124 -0
  56. basic_memory/cli/commands/command_utils.py +77 -0
  57. basic_memory/cli/commands/db.py +44 -0
  58. basic_memory/cli/commands/format.py +198 -0
  59. basic_memory/cli/commands/import_chatgpt.py +84 -0
  60. basic_memory/cli/commands/import_claude_conversations.py +87 -0
  61. basic_memory/cli/commands/import_claude_projects.py +86 -0
  62. basic_memory/cli/commands/import_memory_json.py +87 -0
  63. basic_memory/cli/commands/mcp.py +76 -0
  64. basic_memory/cli/commands/project.py +889 -0
  65. basic_memory/cli/commands/status.py +174 -0
  66. basic_memory/cli/commands/telemetry.py +81 -0
  67. basic_memory/cli/commands/tool.py +341 -0
  68. basic_memory/cli/main.py +28 -0
  69. basic_memory/config.py +616 -0
  70. basic_memory/db.py +394 -0
  71. basic_memory/deps.py +705 -0
  72. basic_memory/file_utils.py +478 -0
  73. basic_memory/ignore_utils.py +297 -0
  74. basic_memory/importers/__init__.py +27 -0
  75. basic_memory/importers/base.py +79 -0
  76. basic_memory/importers/chatgpt_importer.py +232 -0
  77. basic_memory/importers/claude_conversations_importer.py +180 -0
  78. basic_memory/importers/claude_projects_importer.py +148 -0
  79. basic_memory/importers/memory_json_importer.py +108 -0
  80. basic_memory/importers/utils.py +61 -0
  81. basic_memory/markdown/__init__.py +21 -0
  82. basic_memory/markdown/entity_parser.py +279 -0
  83. basic_memory/markdown/markdown_processor.py +160 -0
  84. basic_memory/markdown/plugins.py +242 -0
  85. basic_memory/markdown/schemas.py +70 -0
  86. basic_memory/markdown/utils.py +117 -0
  87. basic_memory/mcp/__init__.py +1 -0
  88. basic_memory/mcp/async_client.py +139 -0
  89. basic_memory/mcp/project_context.py +141 -0
  90. basic_memory/mcp/prompts/__init__.py +19 -0
  91. basic_memory/mcp/prompts/ai_assistant_guide.py +70 -0
  92. basic_memory/mcp/prompts/continue_conversation.py +62 -0
  93. basic_memory/mcp/prompts/recent_activity.py +188 -0
  94. basic_memory/mcp/prompts/search.py +57 -0
  95. basic_memory/mcp/prompts/utils.py +162 -0
  96. basic_memory/mcp/resources/ai_assistant_guide.md +283 -0
  97. basic_memory/mcp/resources/project_info.py +71 -0
  98. basic_memory/mcp/server.py +81 -0
  99. basic_memory/mcp/tools/__init__.py +48 -0
  100. basic_memory/mcp/tools/build_context.py +120 -0
  101. basic_memory/mcp/tools/canvas.py +152 -0
  102. basic_memory/mcp/tools/chatgpt_tools.py +190 -0
  103. basic_memory/mcp/tools/delete_note.py +242 -0
  104. basic_memory/mcp/tools/edit_note.py +324 -0
  105. basic_memory/mcp/tools/list_directory.py +168 -0
  106. basic_memory/mcp/tools/move_note.py +551 -0
  107. basic_memory/mcp/tools/project_management.py +201 -0
  108. basic_memory/mcp/tools/read_content.py +281 -0
  109. basic_memory/mcp/tools/read_note.py +267 -0
  110. basic_memory/mcp/tools/recent_activity.py +534 -0
  111. basic_memory/mcp/tools/search.py +385 -0
  112. basic_memory/mcp/tools/utils.py +540 -0
  113. basic_memory/mcp/tools/view_note.py +78 -0
  114. basic_memory/mcp/tools/write_note.py +230 -0
  115. basic_memory/models/__init__.py +15 -0
  116. basic_memory/models/base.py +10 -0
  117. basic_memory/models/knowledge.py +226 -0
  118. basic_memory/models/project.py +87 -0
  119. basic_memory/models/search.py +85 -0
  120. basic_memory/repository/__init__.py +11 -0
  121. basic_memory/repository/entity_repository.py +503 -0
  122. basic_memory/repository/observation_repository.py +73 -0
  123. basic_memory/repository/postgres_search_repository.py +379 -0
  124. basic_memory/repository/project_info_repository.py +10 -0
  125. basic_memory/repository/project_repository.py +128 -0
  126. basic_memory/repository/relation_repository.py +146 -0
  127. basic_memory/repository/repository.py +385 -0
  128. basic_memory/repository/search_index_row.py +95 -0
  129. basic_memory/repository/search_repository.py +94 -0
  130. basic_memory/repository/search_repository_base.py +241 -0
  131. basic_memory/repository/sqlite_search_repository.py +439 -0
  132. basic_memory/schemas/__init__.py +86 -0
  133. basic_memory/schemas/base.py +297 -0
  134. basic_memory/schemas/cloud.py +50 -0
  135. basic_memory/schemas/delete.py +37 -0
  136. basic_memory/schemas/directory.py +30 -0
  137. basic_memory/schemas/importer.py +35 -0
  138. basic_memory/schemas/memory.py +285 -0
  139. basic_memory/schemas/project_info.py +212 -0
  140. basic_memory/schemas/prompt.py +90 -0
  141. basic_memory/schemas/request.py +112 -0
  142. basic_memory/schemas/response.py +229 -0
  143. basic_memory/schemas/search.py +117 -0
  144. basic_memory/schemas/sync_report.py +72 -0
  145. basic_memory/schemas/v2/__init__.py +27 -0
  146. basic_memory/schemas/v2/entity.py +129 -0
  147. basic_memory/schemas/v2/resource.py +46 -0
  148. basic_memory/services/__init__.py +8 -0
  149. basic_memory/services/context_service.py +601 -0
  150. basic_memory/services/directory_service.py +308 -0
  151. basic_memory/services/entity_service.py +864 -0
  152. basic_memory/services/exceptions.py +37 -0
  153. basic_memory/services/file_service.py +541 -0
  154. basic_memory/services/initialization.py +216 -0
  155. basic_memory/services/link_resolver.py +121 -0
  156. basic_memory/services/project_service.py +880 -0
  157. basic_memory/services/search_service.py +404 -0
  158. basic_memory/services/service.py +15 -0
  159. basic_memory/sync/__init__.py +6 -0
  160. basic_memory/sync/background_sync.py +26 -0
  161. basic_memory/sync/sync_service.py +1259 -0
  162. basic_memory/sync/watch_service.py +510 -0
  163. basic_memory/telemetry.py +249 -0
  164. basic_memory/templates/prompts/continue_conversation.hbs +110 -0
  165. basic_memory/templates/prompts/search.hbs +101 -0
  166. basic_memory/utils.py +468 -0
  167. basic_memory-0.17.1.dist-info/METADATA +617 -0
  168. basic_memory-0.17.1.dist-info/RECORD +171 -0
  169. basic_memory-0.17.1.dist-info/WHEEL +4 -0
  170. basic_memory-0.17.1.dist-info/entry_points.txt +3 -0
  171. basic_memory-0.17.1.dist-info/licenses/LICENSE +661 -0
@@ -0,0 +1,180 @@
1
+ """Claude conversations import service for Basic Memory."""
2
+
3
+ import logging
4
+ from datetime import datetime
5
+ from pathlib import Path
6
+ from typing import Any, Dict, List
7
+
8
+ from basic_memory.markdown.schemas import EntityFrontmatter, EntityMarkdown
9
+ from basic_memory.importers.base import Importer
10
+ from basic_memory.schemas.importer import ChatImportResult
11
+ from basic_memory.importers.utils import clean_filename, format_timestamp
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class ClaudeConversationsImporter(Importer[ChatImportResult]):
17
+ """Service for importing Claude conversations."""
18
+
19
+ async def import_data(
20
+ self, source_data, destination_folder: str, **kwargs: Any
21
+ ) -> ChatImportResult:
22
+ """Import conversations from Claude JSON export.
23
+
24
+ Args:
25
+ source_data: Path to the Claude conversations.json file.
26
+ destination_folder: Destination folder within the project.
27
+ **kwargs: Additional keyword arguments.
28
+
29
+ Returns:
30
+ ChatImportResult containing statistics and status of the import.
31
+ """
32
+ try:
33
+ # Ensure the destination folder exists
34
+ folder_path = self.ensure_folder_exists(destination_folder)
35
+
36
+ conversations = source_data
37
+
38
+ # Process each conversation
39
+ messages_imported = 0
40
+ chats_imported = 0
41
+
42
+ for chat in conversations:
43
+ # Get name, providing default for unnamed conversations
44
+ chat_name = chat.get("name") or f"Conversation {chat.get('uuid', 'untitled')}"
45
+
46
+ # Convert to entity
47
+ entity = self._format_chat_content(
48
+ base_path=folder_path,
49
+ name=chat_name,
50
+ messages=chat["chat_messages"],
51
+ created_at=chat["created_at"],
52
+ modified_at=chat["updated_at"],
53
+ )
54
+
55
+ # Write file
56
+ file_path = self.base_path / Path(f"{entity.frontmatter.metadata['permalink']}.md")
57
+ await self.write_entity(entity, file_path)
58
+
59
+ chats_imported += 1
60
+ messages_imported += len(chat["chat_messages"])
61
+
62
+ return ChatImportResult(
63
+ import_count={"conversations": chats_imported, "messages": messages_imported},
64
+ success=True,
65
+ conversations=chats_imported,
66
+ messages=messages_imported,
67
+ )
68
+
69
+ except Exception as e: # pragma: no cover
70
+ logger.exception("Failed to import Claude conversations")
71
+ return self.handle_error("Failed to import Claude conversations", e) # pyright: ignore [reportReturnType]
72
+
73
+ def _format_chat_content(
74
+ self,
75
+ base_path: Path,
76
+ name: str,
77
+ messages: List[Dict[str, Any]],
78
+ created_at: str,
79
+ modified_at: str,
80
+ ) -> EntityMarkdown:
81
+ """Convert chat messages to Basic Memory entity format.
82
+
83
+ Args:
84
+ base_path: Base path for the entity.
85
+ name: Chat name.
86
+ messages: List of chat messages.
87
+ created_at: Creation timestamp.
88
+ modified_at: Modification timestamp.
89
+
90
+ Returns:
91
+ EntityMarkdown instance representing the conversation.
92
+ """
93
+ # Generate permalink
94
+ date_prefix = datetime.fromisoformat(created_at.replace("Z", "+00:00")).strftime("%Y%m%d")
95
+ clean_title = clean_filename(name)
96
+ permalink = f"{base_path.name}/{date_prefix}-{clean_title}"
97
+
98
+ # Format content
99
+ content = self._format_chat_markdown(
100
+ name=name,
101
+ messages=messages,
102
+ created_at=created_at,
103
+ modified_at=modified_at,
104
+ permalink=permalink,
105
+ )
106
+
107
+ # Create entity
108
+ entity = EntityMarkdown(
109
+ frontmatter=EntityFrontmatter(
110
+ metadata={
111
+ "type": "conversation",
112
+ "title": name,
113
+ "created": created_at,
114
+ "modified": modified_at,
115
+ "permalink": permalink,
116
+ }
117
+ ),
118
+ content=content,
119
+ )
120
+
121
+ return entity
122
+
123
+ def _format_chat_markdown(
124
+ self,
125
+ name: str,
126
+ messages: List[Dict[str, Any]],
127
+ created_at: str,
128
+ modified_at: str,
129
+ permalink: str,
130
+ ) -> str:
131
+ """Format chat as clean markdown.
132
+
133
+ Args:
134
+ name: Chat name.
135
+ messages: List of chat messages.
136
+ created_at: Creation timestamp.
137
+ modified_at: Modification timestamp.
138
+ permalink: Permalink for the entity.
139
+
140
+ Returns:
141
+ Formatted markdown content.
142
+ """
143
+ # Start with frontmatter and title
144
+ lines = [
145
+ f"# {name}\n",
146
+ ]
147
+
148
+ # Add messages
149
+ for msg in messages:
150
+ # Format timestamp
151
+ ts = format_timestamp(msg["created_at"])
152
+
153
+ # Add message header
154
+ lines.append(f"### {msg['sender'].title()} ({ts})")
155
+
156
+ # Handle message content
157
+ content = msg.get("text", "")
158
+ if msg.get("content"):
159
+ # Filter out None values before joining
160
+ content = " ".join(
161
+ str(c.get("text", ""))
162
+ for c in msg["content"]
163
+ if c and c.get("text") is not None
164
+ )
165
+ lines.append(content)
166
+
167
+ # Handle attachments
168
+ attachments = msg.get("attachments", [])
169
+ for attachment in attachments:
170
+ if "file_name" in attachment:
171
+ lines.append(f"\n**Attachment: {attachment['file_name']}**")
172
+ if "extracted_content" in attachment:
173
+ lines.append("```")
174
+ lines.append(attachment["extracted_content"])
175
+ lines.append("```")
176
+
177
+ # Add spacing between messages
178
+ lines.append("")
179
+
180
+ return "\n".join(lines)
@@ -0,0 +1,148 @@
1
+ """Claude projects import service for Basic Memory."""
2
+
3
+ import logging
4
+ from typing import Any, Dict, Optional
5
+
6
+ from basic_memory.markdown.schemas import EntityFrontmatter, EntityMarkdown
7
+ from basic_memory.importers.base import Importer
8
+ from basic_memory.schemas.importer import ProjectImportResult
9
+ from basic_memory.importers.utils import clean_filename
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class ClaudeProjectsImporter(Importer[ProjectImportResult]):
15
+ """Service for importing Claude projects."""
16
+
17
+ async def import_data(
18
+ self, source_data, destination_folder: str, **kwargs: Any
19
+ ) -> ProjectImportResult:
20
+ """Import projects from Claude JSON export.
21
+
22
+ Args:
23
+ source_path: Path to the Claude projects.json file.
24
+ destination_folder: Base folder for projects within the project.
25
+ **kwargs: Additional keyword arguments.
26
+
27
+ Returns:
28
+ ProjectImportResult containing statistics and status of the import.
29
+ """
30
+ try:
31
+ # Ensure the base folder exists
32
+ base_path = self.base_path
33
+ if destination_folder:
34
+ base_path = self.ensure_folder_exists(destination_folder)
35
+
36
+ projects = source_data
37
+
38
+ # Process each project
39
+ docs_imported = 0
40
+ prompts_imported = 0
41
+
42
+ for project in projects:
43
+ project_dir = clean_filename(project["name"])
44
+
45
+ # Create project directories
46
+ docs_dir = base_path / project_dir / "docs"
47
+ docs_dir.mkdir(parents=True, exist_ok=True)
48
+
49
+ # Import prompt template if it exists
50
+ if prompt_entity := self._format_prompt_markdown(project):
51
+ file_path = base_path / f"{prompt_entity.frontmatter.metadata['permalink']}.md"
52
+ await self.write_entity(prompt_entity, file_path)
53
+ prompts_imported += 1
54
+
55
+ # Import project documents
56
+ for doc in project.get("docs", []):
57
+ entity = self._format_project_markdown(project, doc)
58
+ file_path = base_path / f"{entity.frontmatter.metadata['permalink']}.md"
59
+ await self.write_entity(entity, file_path)
60
+ docs_imported += 1
61
+
62
+ return ProjectImportResult(
63
+ import_count={"documents": docs_imported, "prompts": prompts_imported},
64
+ success=True,
65
+ documents=docs_imported,
66
+ prompts=prompts_imported,
67
+ )
68
+
69
+ except Exception as e: # pragma: no cover
70
+ logger.exception("Failed to import Claude projects")
71
+ return self.handle_error("Failed to import Claude projects", e) # pyright: ignore [reportReturnType]
72
+
73
+ def _format_project_markdown(
74
+ self, project: Dict[str, Any], doc: Dict[str, Any]
75
+ ) -> EntityMarkdown:
76
+ """Format a project document as a Basic Memory entity.
77
+
78
+ Args:
79
+ project: Project data.
80
+ doc: Document data.
81
+
82
+ Returns:
83
+ EntityMarkdown instance representing the document.
84
+ """
85
+ # Extract timestamps
86
+ created_at = doc.get("created_at") or project["created_at"]
87
+ modified_at = project["updated_at"]
88
+
89
+ # Generate clean names for organization
90
+ project_dir = clean_filename(project["name"])
91
+ doc_file = clean_filename(doc["filename"])
92
+
93
+ # Create entity
94
+ entity = EntityMarkdown(
95
+ frontmatter=EntityFrontmatter(
96
+ metadata={
97
+ "type": "project_doc",
98
+ "title": doc["filename"],
99
+ "created": created_at,
100
+ "modified": modified_at,
101
+ "permalink": f"{project_dir}/docs/{doc_file}",
102
+ "project_name": project["name"],
103
+ "project_uuid": project["uuid"],
104
+ "doc_uuid": doc["uuid"],
105
+ }
106
+ ),
107
+ content=doc["content"],
108
+ )
109
+
110
+ return entity
111
+
112
+ def _format_prompt_markdown(self, project: Dict[str, Any]) -> Optional[EntityMarkdown]:
113
+ """Format project prompt template as a Basic Memory entity.
114
+
115
+ Args:
116
+ project: Project data.
117
+
118
+ Returns:
119
+ EntityMarkdown instance representing the prompt template, or None if
120
+ no prompt template exists.
121
+ """
122
+ if not project.get("prompt_template"):
123
+ return None
124
+
125
+ # Extract timestamps
126
+ created_at = project["created_at"]
127
+ modified_at = project["updated_at"]
128
+
129
+ # Generate clean project directory name
130
+ project_dir = clean_filename(project["name"])
131
+
132
+ # Create entity
133
+ entity = EntityMarkdown(
134
+ frontmatter=EntityFrontmatter(
135
+ metadata={
136
+ "type": "prompt_template",
137
+ "title": f"Prompt Template: {project['name']}",
138
+ "created": created_at,
139
+ "modified": modified_at,
140
+ "permalink": f"{project_dir}/prompt-template",
141
+ "project_name": project["name"],
142
+ "project_uuid": project["uuid"],
143
+ }
144
+ ),
145
+ content=f"# Prompt Template: {project['name']}\n\n{project['prompt_template']}",
146
+ )
147
+
148
+ return entity
@@ -0,0 +1,108 @@
1
+ """Memory JSON import service for Basic Memory."""
2
+
3
+ import logging
4
+ from typing import Any, Dict, List
5
+
6
+ from basic_memory.config import get_project_config
7
+ from basic_memory.markdown.schemas import EntityFrontmatter, EntityMarkdown, Observation, Relation
8
+ from basic_memory.importers.base import Importer
9
+ from basic_memory.schemas.importer import EntityImportResult
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class MemoryJsonImporter(Importer[EntityImportResult]):
15
+ """Service for importing memory.json format data."""
16
+
17
+ async def import_data(
18
+ self, source_data, destination_folder: str = "", **kwargs: Any
19
+ ) -> EntityImportResult:
20
+ """Import entities and relations from a memory.json file.
21
+
22
+ Args:
23
+ source_data: Path to the memory.json file.
24
+ destination_folder: Optional destination folder within the project.
25
+ **kwargs: Additional keyword arguments.
26
+
27
+ Returns:
28
+ EntityImportResult containing statistics and status of the import.
29
+ """
30
+ config = get_project_config()
31
+ try:
32
+ # First pass - collect all relations by source entity
33
+ entity_relations: Dict[str, List[Relation]] = {}
34
+ entities: Dict[str, Dict[str, Any]] = {}
35
+ skipped_entities: int = 0
36
+
37
+ # Ensure the base path exists
38
+ base_path = config.home # pragma: no cover
39
+ if destination_folder: # pragma: no cover
40
+ base_path = self.ensure_folder_exists(destination_folder)
41
+
42
+ # First pass - collect entities and relations
43
+ for line in source_data:
44
+ data = line
45
+ if data["type"] == "entity":
46
+ # Handle different possible name keys
47
+ entity_name = data.get("name") or data.get("entityName") or data.get("id")
48
+ if not entity_name:
49
+ logger.warning(f"Entity missing name field: {data}")
50
+ skipped_entities += 1
51
+ continue
52
+ entities[entity_name] = data
53
+ elif data["type"] == "relation":
54
+ # Store relation with its source entity
55
+ source = data.get("from") or data.get("from_id")
56
+ if source not in entity_relations:
57
+ entity_relations[source] = []
58
+ entity_relations[source].append(
59
+ Relation(
60
+ type=data.get("relationType") or data.get("relation_type"),
61
+ target=data.get("to") or data.get("to_id"),
62
+ )
63
+ )
64
+
65
+ # Second pass - create and write entities
66
+ entities_created = 0
67
+ for name, entity_data in entities.items():
68
+ # Get entity type with fallback
69
+ entity_type = entity_data.get("entityType") or entity_data.get("type") or "entity"
70
+
71
+ # Ensure entity type directory exists
72
+ entity_type_dir = base_path / entity_type
73
+ entity_type_dir.mkdir(parents=True, exist_ok=True)
74
+
75
+ # Get observations with fallback to empty list
76
+ observations = entity_data.get("observations", [])
77
+
78
+ entity = EntityMarkdown(
79
+ frontmatter=EntityFrontmatter(
80
+ metadata={
81
+ "type": entity_type,
82
+ "title": name,
83
+ "permalink": f"{entity_type}/{name}",
84
+ }
85
+ ),
86
+ content=f"# {name}\n",
87
+ observations=[Observation(content=obs) for obs in observations],
88
+ relations=entity_relations.get(name, []),
89
+ )
90
+
91
+ # Write entity file
92
+ file_path = base_path / f"{entity_type}/{name}.md"
93
+ await self.write_entity(entity, file_path)
94
+ entities_created += 1
95
+
96
+ relations_count = sum(len(rels) for rels in entity_relations.values())
97
+
98
+ return EntityImportResult(
99
+ import_count={"entities": entities_created, "relations": relations_count},
100
+ success=True,
101
+ entities=entities_created,
102
+ relations=relations_count,
103
+ skipped_entities=skipped_entities,
104
+ )
105
+
106
+ except Exception as e: # pragma: no cover
107
+ logger.exception("Failed to import memory.json")
108
+ return self.handle_error("Failed to import memory.json", e) # pyright: ignore [reportReturnType]
@@ -0,0 +1,61 @@
1
+ """Utility functions for import services."""
2
+
3
+ import re
4
+ from datetime import datetime
5
+ from typing import Any
6
+
7
+
8
+ def clean_filename(name: str | None) -> str: # pragma: no cover
9
+ """Clean a string to be used as a filename.
10
+
11
+ Args:
12
+ name: The string to clean (can be None).
13
+
14
+ Returns:
15
+ A cleaned string suitable for use as a filename.
16
+ """
17
+ # Handle None or empty input
18
+ if not name:
19
+ return "untitled"
20
+ # Replace common punctuation and whitespace with underscores
21
+ name = re.sub(r"[\s\-,.:/\\\[\]\(\)]+", "_", name)
22
+ # Remove any non-alphanumeric or underscore characters
23
+ name = re.sub(r"[^\w]+", "", name)
24
+ # Ensure the name isn't too long
25
+ if len(name) > 100: # pragma: no cover
26
+ name = name[:100]
27
+ # Ensure the name isn't empty
28
+ if not name: # pragma: no cover
29
+ name = "untitled"
30
+ return name
31
+
32
+
33
+ def format_timestamp(timestamp: Any) -> str: # pragma: no cover
34
+ """Format a timestamp for use in a filename or title.
35
+
36
+ Args:
37
+ timestamp: A timestamp in various formats.
38
+
39
+ Returns:
40
+ A formatted string representation of the timestamp.
41
+ """
42
+ if isinstance(timestamp, str):
43
+ try:
44
+ # Try ISO format
45
+ timestamp = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
46
+ except ValueError:
47
+ try:
48
+ # Try unix timestamp as string
49
+ timestamp = datetime.fromtimestamp(float(timestamp)).astimezone()
50
+ except ValueError:
51
+ # Return as is if we can't parse it
52
+ return timestamp
53
+ elif isinstance(timestamp, (int, float)):
54
+ # Unix timestamp
55
+ timestamp = datetime.fromtimestamp(timestamp).astimezone()
56
+
57
+ if isinstance(timestamp, datetime):
58
+ return timestamp.strftime("%Y-%m-%d %H:%M:%S")
59
+
60
+ # Return as is if we can't format it
61
+ return str(timestamp) # pragma: no cover
@@ -0,0 +1,21 @@
1
+ """Base package for markdown parsing."""
2
+
3
+ from basic_memory.file_utils import ParseError
4
+ from basic_memory.markdown.entity_parser import EntityParser
5
+ from basic_memory.markdown.markdown_processor import MarkdownProcessor
6
+ from basic_memory.markdown.schemas import (
7
+ EntityMarkdown,
8
+ EntityFrontmatter,
9
+ Observation,
10
+ Relation,
11
+ )
12
+
13
+ __all__ = [
14
+ "EntityMarkdown",
15
+ "EntityFrontmatter",
16
+ "EntityParser",
17
+ "MarkdownProcessor",
18
+ "Observation",
19
+ "Relation",
20
+ "ParseError",
21
+ ]