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,503 @@
1
+ """Repository for managing entities in the knowledge graph."""
2
+
3
+ from pathlib import Path
4
+ from typing import List, Optional, Sequence, Union, Any
5
+
6
+
7
+ from loguru import logger
8
+ from sqlalchemy import select
9
+ from sqlalchemy.exc import IntegrityError
10
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
11
+ from sqlalchemy.orm import selectinload
12
+ from sqlalchemy.orm.interfaces import LoaderOption
13
+ from sqlalchemy.engine import Row
14
+
15
+ from basic_memory import db
16
+ from basic_memory.models.knowledge import Entity, Observation, Relation
17
+ from basic_memory.repository.repository import Repository
18
+
19
+
20
+ class EntityRepository(Repository[Entity]):
21
+ """Repository for Entity model.
22
+
23
+ Note: All file paths are stored as strings in the database. Convert Path objects
24
+ to strings before passing to repository methods.
25
+ """
26
+
27
+ def __init__(self, session_maker: async_sessionmaker[AsyncSession], project_id: int):
28
+ """Initialize with session maker and project_id filter.
29
+
30
+ Args:
31
+ session_maker: SQLAlchemy session maker
32
+ project_id: Project ID to filter all operations by
33
+ """
34
+ super().__init__(session_maker, Entity, project_id=project_id)
35
+
36
+ async def get_by_id(self, entity_id: int) -> Optional[Entity]:
37
+ """Get entity by numeric ID.
38
+
39
+ Args:
40
+ entity_id: Numeric entity ID
41
+
42
+ Returns:
43
+ Entity if found, None otherwise
44
+ """
45
+ async with db.scoped_session(self.session_maker) as session:
46
+ return await self.select_by_id(session, entity_id)
47
+
48
+ async def get_by_permalink(self, permalink: str) -> Optional[Entity]:
49
+ """Get entity by permalink.
50
+
51
+ Args:
52
+ permalink: Unique identifier for the entity
53
+ """
54
+ query = self.select().where(Entity.permalink == permalink).options(*self.get_load_options())
55
+ return await self.find_one(query)
56
+
57
+ async def get_by_title(self, title: str) -> Sequence[Entity]:
58
+ """Get entity by title.
59
+
60
+ Args:
61
+ title: Title of the entity to find
62
+ """
63
+ query = self.select().where(Entity.title == title).options(*self.get_load_options())
64
+ result = await self.execute_query(query)
65
+ return list(result.scalars().all())
66
+
67
+ async def get_by_file_path(self, file_path: Union[Path, str]) -> Optional[Entity]:
68
+ """Get entity by file_path.
69
+
70
+ Args:
71
+ file_path: Path to the entity file (will be converted to string internally)
72
+ """
73
+ query = (
74
+ self.select()
75
+ .where(Entity.file_path == Path(file_path).as_posix())
76
+ .options(*self.get_load_options())
77
+ )
78
+ return await self.find_one(query)
79
+
80
+ # -------------------------------------------------------------------------
81
+ # Lightweight methods for permalink resolution (no eager loading)
82
+ # -------------------------------------------------------------------------
83
+
84
+ async def permalink_exists(self, permalink: str) -> bool:
85
+ """Check if a permalink exists without loading the full entity.
86
+
87
+ This is much faster than get_by_permalink() as it skips eager loading
88
+ of observations and relations. Use for existence checks in bulk operations.
89
+
90
+ Args:
91
+ permalink: Permalink to check
92
+
93
+ Returns:
94
+ True if permalink exists, False otherwise
95
+ """
96
+ query = select(Entity.id).where(Entity.permalink == permalink).limit(1)
97
+ query = self._add_project_filter(query)
98
+ result = await self.execute_query(query, use_query_options=False)
99
+ return result.scalar_one_or_none() is not None
100
+
101
+ async def get_file_path_for_permalink(self, permalink: str) -> Optional[str]:
102
+ """Get the file_path for a permalink without loading the full entity.
103
+
104
+ Use when you only need the file_path, not the full entity with relations.
105
+
106
+ Args:
107
+ permalink: Permalink to look up
108
+
109
+ Returns:
110
+ file_path string if found, None otherwise
111
+ """
112
+ query = select(Entity.file_path).where(Entity.permalink == permalink)
113
+ query = self._add_project_filter(query)
114
+ result = await self.execute_query(query, use_query_options=False)
115
+ return result.scalar_one_or_none()
116
+
117
+ async def get_permalink_for_file_path(self, file_path: Union[Path, str]) -> Optional[str]:
118
+ """Get the permalink for a file_path without loading the full entity.
119
+
120
+ Use when you only need the permalink, not the full entity with relations.
121
+
122
+ Args:
123
+ file_path: File path to look up
124
+
125
+ Returns:
126
+ permalink string if found, None otherwise
127
+ """
128
+ query = select(Entity.permalink).where(Entity.file_path == Path(file_path).as_posix())
129
+ query = self._add_project_filter(query)
130
+ result = await self.execute_query(query, use_query_options=False)
131
+ return result.scalar_one_or_none()
132
+
133
+ async def get_all_permalinks(self) -> List[str]:
134
+ """Get all permalinks for this project.
135
+
136
+ Optimized for bulk operations - returns only permalink strings
137
+ without loading entities or relationships.
138
+
139
+ Returns:
140
+ List of all permalinks in the project
141
+ """
142
+ query = select(Entity.permalink)
143
+ query = self._add_project_filter(query)
144
+ result = await self.execute_query(query, use_query_options=False)
145
+ return list(result.scalars().all())
146
+
147
+ async def get_permalink_to_file_path_map(self) -> dict[str, str]:
148
+ """Get a mapping of permalink -> file_path for all entities.
149
+
150
+ Optimized for bulk permalink resolution - loads minimal data in one query.
151
+
152
+ Returns:
153
+ Dict mapping permalink to file_path
154
+ """
155
+ query = select(Entity.permalink, Entity.file_path)
156
+ query = self._add_project_filter(query)
157
+ result = await self.execute_query(query, use_query_options=False)
158
+ return {row.permalink: row.file_path for row in result.all()}
159
+
160
+ async def get_file_path_to_permalink_map(self) -> dict[str, str]:
161
+ """Get a mapping of file_path -> permalink for all entities.
162
+
163
+ Optimized for bulk permalink resolution - loads minimal data in one query.
164
+
165
+ Returns:
166
+ Dict mapping file_path to permalink
167
+ """
168
+ query = select(Entity.file_path, Entity.permalink)
169
+ query = self._add_project_filter(query)
170
+ result = await self.execute_query(query, use_query_options=False)
171
+ return {row.file_path: row.permalink for row in result.all()}
172
+
173
+ async def get_by_file_paths(
174
+ self, session: AsyncSession, file_paths: Sequence[Union[Path, str]]
175
+ ) -> List[Row[Any]]:
176
+ """Get file paths and checksums for multiple entities (optimized for change detection).
177
+
178
+ Only queries file_path and checksum columns, skips loading full entities and relationships.
179
+ This is much faster than loading complete Entity objects when you only need checksums.
180
+
181
+ Args:
182
+ session: Database session to use for the query
183
+ file_paths: List of file paths to query
184
+
185
+ Returns:
186
+ List of (file_path, checksum) tuples for matching entities
187
+ """
188
+ if not file_paths:
189
+ return []
190
+
191
+ # Convert all paths to POSIX strings for consistent comparison
192
+ posix_paths = [Path(fp).as_posix() for fp in file_paths]
193
+
194
+ # Query ONLY file_path and checksum columns (not full Entity objects)
195
+ query = select(Entity.file_path, Entity.checksum).where(Entity.file_path.in_(posix_paths))
196
+ query = self._add_project_filter(query)
197
+
198
+ result = await session.execute(query)
199
+ return list(result.all())
200
+
201
+ async def find_by_checksum(self, checksum: str) -> Sequence[Entity]:
202
+ """Find entities with the given checksum.
203
+
204
+ Used for move detection - finds entities that may have been moved to a new path.
205
+ Multiple entities may have the same checksum if files were copied.
206
+
207
+ Args:
208
+ checksum: File content checksum to search for
209
+
210
+ Returns:
211
+ Sequence of entities with matching checksum (may be empty)
212
+ """
213
+ query = self.select().where(Entity.checksum == checksum)
214
+ # Don't load relationships for move detection - we only need file_path and checksum
215
+ result = await self.execute_query(query, use_query_options=False)
216
+ return list(result.scalars().all())
217
+
218
+ async def find_by_checksums(self, checksums: Sequence[str]) -> Sequence[Entity]:
219
+ """Find entities with any of the given checksums (batch query for move detection).
220
+
221
+ This is a batch-optimized version of find_by_checksum() that queries multiple checksums
222
+ in a single database query. Used for efficient move detection in cloud indexing.
223
+
224
+ Performance: For 1000 new files, this makes 1 query vs 1000 individual queries (~100x faster).
225
+
226
+ Example:
227
+ When processing new files, we check if any are actually moved files by finding
228
+ entities with matching checksums at different paths.
229
+
230
+ Args:
231
+ checksums: List of file content checksums to search for
232
+
233
+ Returns:
234
+ Sequence of entities with matching checksums (may be empty).
235
+ Multiple entities may have the same checksum if files were copied.
236
+ """
237
+ if not checksums:
238
+ return []
239
+
240
+ # Query: SELECT * FROM entities WHERE checksum IN (checksum1, checksum2, ...)
241
+ query = self.select().where(Entity.checksum.in_(checksums))
242
+ # Don't load relationships for move detection - we only need file_path and checksum
243
+ result = await self.execute_query(query, use_query_options=False)
244
+ return list(result.scalars().all())
245
+
246
+ async def delete_by_file_path(self, file_path: Union[Path, str]) -> bool:
247
+ """Delete entity with the provided file_path.
248
+
249
+ Args:
250
+ file_path: Path to the entity file (will be converted to string internally)
251
+ """
252
+ return await self.delete_by_fields(file_path=Path(file_path).as_posix())
253
+
254
+ def get_load_options(self) -> List[LoaderOption]:
255
+ """Get SQLAlchemy loader options for eager loading relationships."""
256
+ return [
257
+ selectinload(Entity.observations).selectinload(Observation.entity),
258
+ # Load from_relations and both entities for each relation
259
+ selectinload(Entity.outgoing_relations).selectinload(Relation.from_entity),
260
+ selectinload(Entity.outgoing_relations).selectinload(Relation.to_entity),
261
+ # Load to_relations and both entities for each relation
262
+ selectinload(Entity.incoming_relations).selectinload(Relation.from_entity),
263
+ selectinload(Entity.incoming_relations).selectinload(Relation.to_entity),
264
+ ]
265
+
266
+ async def find_by_permalinks(self, permalinks: List[str]) -> Sequence[Entity]:
267
+ """Find multiple entities by their permalink.
268
+
269
+ Args:
270
+ permalinks: List of permalink strings to find
271
+ """
272
+ # Handle empty input explicitly
273
+ if not permalinks:
274
+ return []
275
+
276
+ # Use existing select pattern
277
+ query = (
278
+ self.select().options(*self.get_load_options()).where(Entity.permalink.in_(permalinks))
279
+ )
280
+
281
+ result = await self.execute_query(query)
282
+ return list(result.scalars().all())
283
+
284
+ async def upsert_entity(self, entity: Entity) -> Entity:
285
+ """Insert or update entity using simple try/catch with database-level conflict resolution.
286
+
287
+ Handles file_path race conditions by checking for existing entity on IntegrityError.
288
+ For permalink conflicts, generates a unique permalink with numeric suffix.
289
+
290
+ Args:
291
+ entity: The entity to insert or update
292
+
293
+ Returns:
294
+ The inserted or updated entity
295
+ """
296
+ async with db.scoped_session(self.session_maker) as session:
297
+ # Set project_id if applicable and not already set
298
+ self._set_project_id_if_needed(entity)
299
+
300
+ # Try simple insert first
301
+ try:
302
+ session.add(entity)
303
+ await session.flush()
304
+
305
+ # Return with relationships loaded
306
+ query = (
307
+ self.select()
308
+ .where(Entity.file_path == entity.file_path)
309
+ .options(*self.get_load_options())
310
+ )
311
+ result = await session.execute(query)
312
+ found = result.scalar_one_or_none()
313
+ if not found: # pragma: no cover
314
+ raise RuntimeError(
315
+ f"Failed to retrieve entity after insert: {entity.file_path}"
316
+ )
317
+ return found
318
+
319
+ except IntegrityError as e:
320
+ # Check if this is a FOREIGN KEY constraint failure
321
+ # SQLite: "FOREIGN KEY constraint failed"
322
+ # Postgres: "violates foreign key constraint"
323
+ error_str = str(e)
324
+ if (
325
+ "FOREIGN KEY constraint failed" in error_str
326
+ or "violates foreign key constraint" in error_str
327
+ ):
328
+ # Import locally to avoid circular dependency (repository -> services -> repository)
329
+ from basic_memory.services.exceptions import SyncFatalError
330
+
331
+ # Project doesn't exist in database - this is a fatal sync error
332
+ raise SyncFatalError(
333
+ f"Cannot sync file '{entity.file_path}': "
334
+ f"project_id={entity.project_id} does not exist in database. "
335
+ f"The project may have been deleted. This sync will be terminated."
336
+ ) from e
337
+
338
+ await session.rollback()
339
+
340
+ # Re-query after rollback to get a fresh, attached entity
341
+ existing_result = await session.execute(
342
+ select(Entity)
343
+ .where(
344
+ Entity.file_path == entity.file_path, Entity.project_id == entity.project_id
345
+ )
346
+ .options(*self.get_load_options())
347
+ )
348
+ existing_entity = existing_result.scalar_one_or_none()
349
+
350
+ if existing_entity:
351
+ # File path conflict - update the existing entity
352
+ logger.debug(
353
+ f"Resolving file_path conflict for {entity.file_path}, "
354
+ f"entity_id={existing_entity.id}, observations={len(entity.observations)}"
355
+ )
356
+ # Use merge to avoid session state conflicts
357
+ # Set the ID to update existing entity
358
+ entity.id = existing_entity.id
359
+
360
+ # Ensure observations reference the correct entity_id
361
+ for obs in entity.observations:
362
+ obs.entity_id = existing_entity.id
363
+ # Clear any existing ID to force INSERT as new observation
364
+ obs.id = None
365
+
366
+ # Merge the entity which will update the existing one
367
+ merged_entity = await session.merge(entity)
368
+
369
+ await session.commit()
370
+
371
+ # Re-query to get proper relationships loaded
372
+ final_result = await session.execute(
373
+ select(Entity)
374
+ .where(Entity.id == merged_entity.id)
375
+ .options(*self.get_load_options())
376
+ )
377
+ return final_result.scalar_one()
378
+
379
+ else:
380
+ # No file_path conflict - must be permalink conflict
381
+ # Generate unique permalink and retry
382
+ entity = await self._handle_permalink_conflict(entity, session)
383
+ return entity
384
+
385
+ async def get_all_file_paths(self) -> List[str]:
386
+ """Get all file paths for this project - optimized for deletion detection.
387
+
388
+ Returns only file_path strings without loading entities or relationships.
389
+ Used by streaming sync to detect deleted files efficiently.
390
+
391
+ Returns:
392
+ List of file_path strings for all entities in the project
393
+ """
394
+ query = select(Entity.file_path)
395
+ query = self._add_project_filter(query)
396
+
397
+ result = await self.execute_query(query, use_query_options=False)
398
+ return list(result.scalars().all())
399
+
400
+ async def get_distinct_directories(self) -> List[str]:
401
+ """Extract unique directory paths from file_path column.
402
+
403
+ Optimized method for getting directory structure without loading full entities
404
+ or relationships. Returns a sorted list of unique directory paths.
405
+
406
+ Returns:
407
+ List of unique directory paths (e.g., ["notes", "notes/meetings", "specs"])
408
+ """
409
+ # Query only file_path column, no entity objects or relationships
410
+ query = select(Entity.file_path).distinct()
411
+ query = self._add_project_filter(query)
412
+
413
+ # Execute with use_query_options=False to skip eager loading
414
+ result = await self.execute_query(query, use_query_options=False)
415
+ file_paths = [row for row in result.scalars().all()]
416
+
417
+ # Parse file paths to extract unique directories
418
+ directories = set()
419
+ for file_path in file_paths:
420
+ parts = [p for p in file_path.split("/") if p]
421
+ # Add all parent directories (exclude filename which is the last part)
422
+ for i in range(len(parts) - 1):
423
+ dir_path = "/".join(parts[: i + 1])
424
+ directories.add(dir_path)
425
+
426
+ return sorted(directories)
427
+
428
+ async def find_by_directory_prefix(self, directory_prefix: str) -> Sequence[Entity]:
429
+ """Find entities whose file_path starts with the given directory prefix.
430
+
431
+ Optimized method for listing directory contents without loading all entities.
432
+ Uses SQL LIKE pattern matching to filter entities by directory path.
433
+
434
+ Args:
435
+ directory_prefix: Directory path prefix (e.g., "docs", "docs/guides")
436
+ Empty string returns all entities (root directory)
437
+
438
+ Returns:
439
+ Sequence of entities in the specified directory and subdirectories
440
+ """
441
+ # Build SQL LIKE pattern
442
+ if directory_prefix == "" or directory_prefix == "/":
443
+ # Root directory - return all entities
444
+ return await self.find_all()
445
+
446
+ # Remove leading/trailing slashes for consistency
447
+ directory_prefix = directory_prefix.strip("/")
448
+
449
+ # Query entities with file_path starting with prefix
450
+ # Pattern matches "prefix/" to ensure we get files IN the directory,
451
+ # not just files whose names start with the prefix
452
+ pattern = f"{directory_prefix}/%"
453
+
454
+ query = self.select().where(Entity.file_path.like(pattern))
455
+
456
+ # Skip eager loading - we only need basic entity fields for directory trees
457
+ result = await self.execute_query(query, use_query_options=False)
458
+ return list(result.scalars().all())
459
+
460
+ async def _handle_permalink_conflict(self, entity: Entity, session: AsyncSession) -> Entity:
461
+ """Handle permalink conflicts by generating a unique permalink."""
462
+ base_permalink = entity.permalink
463
+ suffix = 1
464
+
465
+ # Find a unique permalink
466
+ while True:
467
+ test_permalink = f"{base_permalink}-{suffix}"
468
+ existing = await session.execute(
469
+ select(Entity).where(
470
+ Entity.permalink == test_permalink, Entity.project_id == entity.project_id
471
+ )
472
+ )
473
+ if existing.scalar_one_or_none() is None:
474
+ # Found unique permalink
475
+ entity.permalink = test_permalink
476
+ break
477
+ suffix += 1
478
+
479
+ # Insert with unique permalink
480
+ session.add(entity)
481
+ try:
482
+ await session.flush()
483
+ except IntegrityError as e:
484
+ # Check if this is a FOREIGN KEY constraint failure
485
+ # SQLite: "FOREIGN KEY constraint failed"
486
+ # Postgres: "violates foreign key constraint"
487
+ error_str = str(e)
488
+ if (
489
+ "FOREIGN KEY constraint failed" in error_str
490
+ or "violates foreign key constraint" in error_str
491
+ ):
492
+ # Import locally to avoid circular dependency (repository -> services -> repository)
493
+ from basic_memory.services.exceptions import SyncFatalError
494
+
495
+ # Project doesn't exist in database - this is a fatal sync error
496
+ raise SyncFatalError(
497
+ f"Cannot sync file '{entity.file_path}': "
498
+ f"project_id={entity.project_id} does not exist in database. "
499
+ f"The project may have been deleted. This sync will be terminated."
500
+ ) from e
501
+ # Re-raise if not a foreign key error
502
+ raise
503
+ return entity
@@ -0,0 +1,73 @@
1
+ """Repository for managing Observation objects."""
2
+
3
+ from typing import Dict, List, Sequence
4
+
5
+
6
+ from sqlalchemy import select
7
+ from sqlalchemy.ext.asyncio import async_sessionmaker
8
+
9
+ from basic_memory.models import Observation
10
+ from basic_memory.repository.repository import Repository
11
+
12
+
13
+ class ObservationRepository(Repository[Observation]):
14
+ """Repository for Observation model with memory-specific operations."""
15
+
16
+ def __init__(self, session_maker: async_sessionmaker, project_id: int):
17
+ """Initialize with session maker and project_id filter.
18
+
19
+ Args:
20
+ session_maker: SQLAlchemy session maker
21
+ project_id: Project ID to filter all operations by
22
+ """
23
+ super().__init__(session_maker, Observation, project_id=project_id)
24
+
25
+ async def find_by_entity(self, entity_id: int) -> Sequence[Observation]:
26
+ """Find all observations for a specific entity."""
27
+ query = select(Observation).filter(Observation.entity_id == entity_id)
28
+ result = await self.execute_query(query)
29
+ return result.scalars().all()
30
+
31
+ async def find_by_context(self, context: str) -> Sequence[Observation]:
32
+ """Find observations with a specific context."""
33
+ query = select(Observation).filter(Observation.context == context)
34
+ result = await self.execute_query(query)
35
+ return result.scalars().all()
36
+
37
+ async def find_by_category(self, category: str) -> Sequence[Observation]:
38
+ """Find observations with a specific context."""
39
+ query = select(Observation).filter(Observation.category == category)
40
+ result = await self.execute_query(query)
41
+ return result.scalars().all()
42
+
43
+ async def observation_categories(self) -> Sequence[str]:
44
+ """Return a list of all observation categories."""
45
+ query = select(Observation.category).distinct()
46
+ result = await self.execute_query(query, use_query_options=False)
47
+ return result.scalars().all()
48
+
49
+ async def find_by_entities(self, entity_ids: List[int]) -> Dict[int, List[Observation]]:
50
+ """Find all observations for multiple entities in a single query.
51
+
52
+ Args:
53
+ entity_ids: List of entity IDs to fetch observations for
54
+
55
+ Returns:
56
+ Dictionary mapping entity_id to list of observations
57
+ """
58
+ if not entity_ids: # pragma: no cover
59
+ return {}
60
+
61
+ # Query observations for all entities in the list
62
+ query = select(Observation).filter(Observation.entity_id.in_(entity_ids))
63
+ result = await self.execute_query(query)
64
+ observations = result.scalars().all()
65
+
66
+ # Group observations by entity_id
67
+ observations_by_entity = {}
68
+ for obs in observations:
69
+ if obs.entity_id not in observations_by_entity:
70
+ observations_by_entity[obs.entity_id] = []
71
+ observations_by_entity[obs.entity_id].append(obs)
72
+
73
+ return observations_by_entity