basic-memory 0.7.0__py3-none-any.whl → 0.17.4__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.

Potentially problematic release.


This version of basic-memory might be problematic. Click here for more details.

Files changed (195) hide show
  1. basic_memory/__init__.py +5 -1
  2. basic_memory/alembic/alembic.ini +119 -0
  3. basic_memory/alembic/env.py +130 -20
  4. basic_memory/alembic/migrations.py +4 -9
  5. basic_memory/alembic/versions/314f1ea54dc4_add_postgres_full_text_search_support_.py +131 -0
  6. basic_memory/alembic/versions/502b60eaa905_remove_required_from_entity_permalink.py +51 -0
  7. basic_memory/alembic/versions/5fe1ab1ccebe_add_projects_table.py +120 -0
  8. basic_memory/alembic/versions/647e7a75e2cd_project_constraint_fix.py +112 -0
  9. basic_memory/alembic/versions/6830751f5fb6_merge_multiple_heads.py +24 -0
  10. basic_memory/alembic/versions/9d9c1cb7d8f5_add_mtime_and_size_columns_to_entity_.py +49 -0
  11. basic_memory/alembic/versions/a1b2c3d4e5f6_fix_project_foreign_keys.py +49 -0
  12. basic_memory/alembic/versions/a2b3c4d5e6f7_add_search_index_entity_cascade.py +56 -0
  13. basic_memory/alembic/versions/b3c3938bacdb_relation_to_name_unique_index.py +44 -0
  14. basic_memory/alembic/versions/cc7172b46608_update_search_index_schema.py +113 -0
  15. basic_memory/alembic/versions/e7e1f4367280_add_scan_watermark_tracking_to_project.py +37 -0
  16. basic_memory/alembic/versions/f8a9b2c3d4e5_add_pg_trgm_for_fuzzy_link_resolution.py +239 -0
  17. basic_memory/alembic/versions/g9a0b3c4d5e6_add_external_id_to_project_and_entity.py +173 -0
  18. basic_memory/api/app.py +87 -20
  19. basic_memory/api/container.py +133 -0
  20. basic_memory/api/routers/__init__.py +4 -1
  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 +180 -23
  24. basic_memory/api/routers/management_router.py +80 -0
  25. basic_memory/api/routers/memory_router.py +9 -64
  26. basic_memory/api/routers/project_router.py +460 -0
  27. basic_memory/api/routers/prompt_router.py +260 -0
  28. basic_memory/api/routers/resource_router.py +136 -11
  29. basic_memory/api/routers/search_router.py +5 -5
  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 +181 -0
  36. basic_memory/api/v2/routers/knowledge_router.py +427 -0
  37. basic_memory/api/v2/routers/memory_router.py +130 -0
  38. basic_memory/api/v2/routers/project_router.py +359 -0
  39. basic_memory/api/v2/routers/prompt_router.py +269 -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/app.py +80 -10
  43. basic_memory/cli/auth.py +300 -0
  44. basic_memory/cli/commands/__init__.py +15 -2
  45. basic_memory/cli/commands/cloud/__init__.py +6 -0
  46. basic_memory/cli/commands/cloud/api_client.py +127 -0
  47. basic_memory/cli/commands/cloud/bisync_commands.py +110 -0
  48. basic_memory/cli/commands/cloud/cloud_utils.py +108 -0
  49. basic_memory/cli/commands/cloud/core_commands.py +195 -0
  50. basic_memory/cli/commands/cloud/rclone_commands.py +397 -0
  51. basic_memory/cli/commands/cloud/rclone_config.py +110 -0
  52. basic_memory/cli/commands/cloud/rclone_installer.py +263 -0
  53. basic_memory/cli/commands/cloud/upload.py +240 -0
  54. basic_memory/cli/commands/cloud/upload_command.py +124 -0
  55. basic_memory/cli/commands/command_utils.py +99 -0
  56. basic_memory/cli/commands/db.py +87 -12
  57. basic_memory/cli/commands/format.py +198 -0
  58. basic_memory/cli/commands/import_chatgpt.py +47 -223
  59. basic_memory/cli/commands/import_claude_conversations.py +48 -171
  60. basic_memory/cli/commands/import_claude_projects.py +53 -160
  61. basic_memory/cli/commands/import_memory_json.py +55 -111
  62. basic_memory/cli/commands/mcp.py +67 -11
  63. basic_memory/cli/commands/project.py +889 -0
  64. basic_memory/cli/commands/status.py +52 -34
  65. basic_memory/cli/commands/telemetry.py +81 -0
  66. basic_memory/cli/commands/tool.py +341 -0
  67. basic_memory/cli/container.py +84 -0
  68. basic_memory/cli/main.py +14 -6
  69. basic_memory/config.py +580 -26
  70. basic_memory/db.py +285 -28
  71. basic_memory/deps/__init__.py +293 -0
  72. basic_memory/deps/config.py +26 -0
  73. basic_memory/deps/db.py +56 -0
  74. basic_memory/deps/importers.py +200 -0
  75. basic_memory/deps/projects.py +238 -0
  76. basic_memory/deps/repositories.py +179 -0
  77. basic_memory/deps/services.py +480 -0
  78. basic_memory/deps.py +16 -185
  79. basic_memory/file_utils.py +318 -54
  80. basic_memory/ignore_utils.py +297 -0
  81. basic_memory/importers/__init__.py +27 -0
  82. basic_memory/importers/base.py +100 -0
  83. basic_memory/importers/chatgpt_importer.py +245 -0
  84. basic_memory/importers/claude_conversations_importer.py +192 -0
  85. basic_memory/importers/claude_projects_importer.py +184 -0
  86. basic_memory/importers/memory_json_importer.py +128 -0
  87. basic_memory/importers/utils.py +61 -0
  88. basic_memory/markdown/entity_parser.py +182 -23
  89. basic_memory/markdown/markdown_processor.py +70 -7
  90. basic_memory/markdown/plugins.py +43 -23
  91. basic_memory/markdown/schemas.py +1 -1
  92. basic_memory/markdown/utils.py +38 -14
  93. basic_memory/mcp/async_client.py +135 -4
  94. basic_memory/mcp/clients/__init__.py +28 -0
  95. basic_memory/mcp/clients/directory.py +70 -0
  96. basic_memory/mcp/clients/knowledge.py +176 -0
  97. basic_memory/mcp/clients/memory.py +120 -0
  98. basic_memory/mcp/clients/project.py +89 -0
  99. basic_memory/mcp/clients/resource.py +71 -0
  100. basic_memory/mcp/clients/search.py +65 -0
  101. basic_memory/mcp/container.py +110 -0
  102. basic_memory/mcp/project_context.py +155 -0
  103. basic_memory/mcp/prompts/__init__.py +19 -0
  104. basic_memory/mcp/prompts/ai_assistant_guide.py +70 -0
  105. basic_memory/mcp/prompts/continue_conversation.py +62 -0
  106. basic_memory/mcp/prompts/recent_activity.py +188 -0
  107. basic_memory/mcp/prompts/search.py +57 -0
  108. basic_memory/mcp/prompts/utils.py +162 -0
  109. basic_memory/mcp/resources/ai_assistant_guide.md +283 -0
  110. basic_memory/mcp/resources/project_info.py +71 -0
  111. basic_memory/mcp/server.py +61 -9
  112. basic_memory/mcp/tools/__init__.py +33 -21
  113. basic_memory/mcp/tools/build_context.py +120 -0
  114. basic_memory/mcp/tools/canvas.py +152 -0
  115. basic_memory/mcp/tools/chatgpt_tools.py +190 -0
  116. basic_memory/mcp/tools/delete_note.py +249 -0
  117. basic_memory/mcp/tools/edit_note.py +325 -0
  118. basic_memory/mcp/tools/list_directory.py +157 -0
  119. basic_memory/mcp/tools/move_note.py +549 -0
  120. basic_memory/mcp/tools/project_management.py +204 -0
  121. basic_memory/mcp/tools/read_content.py +281 -0
  122. basic_memory/mcp/tools/read_note.py +265 -0
  123. basic_memory/mcp/tools/recent_activity.py +528 -0
  124. basic_memory/mcp/tools/search.py +377 -24
  125. basic_memory/mcp/tools/utils.py +402 -16
  126. basic_memory/mcp/tools/view_note.py +78 -0
  127. basic_memory/mcp/tools/write_note.py +230 -0
  128. basic_memory/models/__init__.py +3 -2
  129. basic_memory/models/knowledge.py +82 -17
  130. basic_memory/models/project.py +93 -0
  131. basic_memory/models/search.py +68 -8
  132. basic_memory/project_resolver.py +222 -0
  133. basic_memory/repository/__init__.py +2 -0
  134. basic_memory/repository/entity_repository.py +437 -8
  135. basic_memory/repository/observation_repository.py +36 -3
  136. basic_memory/repository/postgres_search_repository.py +451 -0
  137. basic_memory/repository/project_info_repository.py +10 -0
  138. basic_memory/repository/project_repository.py +140 -0
  139. basic_memory/repository/relation_repository.py +79 -4
  140. basic_memory/repository/repository.py +148 -29
  141. basic_memory/repository/search_index_row.py +95 -0
  142. basic_memory/repository/search_repository.py +79 -268
  143. basic_memory/repository/search_repository_base.py +241 -0
  144. basic_memory/repository/sqlite_search_repository.py +437 -0
  145. basic_memory/runtime.py +61 -0
  146. basic_memory/schemas/__init__.py +22 -9
  147. basic_memory/schemas/base.py +131 -12
  148. basic_memory/schemas/cloud.py +50 -0
  149. basic_memory/schemas/directory.py +31 -0
  150. basic_memory/schemas/importer.py +35 -0
  151. basic_memory/schemas/memory.py +194 -25
  152. basic_memory/schemas/project_info.py +213 -0
  153. basic_memory/schemas/prompt.py +90 -0
  154. basic_memory/schemas/request.py +56 -2
  155. basic_memory/schemas/response.py +85 -28
  156. basic_memory/schemas/search.py +36 -35
  157. basic_memory/schemas/sync_report.py +72 -0
  158. basic_memory/schemas/v2/__init__.py +27 -0
  159. basic_memory/schemas/v2/entity.py +133 -0
  160. basic_memory/schemas/v2/resource.py +47 -0
  161. basic_memory/services/__init__.py +2 -1
  162. basic_memory/services/context_service.py +451 -138
  163. basic_memory/services/directory_service.py +310 -0
  164. basic_memory/services/entity_service.py +636 -71
  165. basic_memory/services/exceptions.py +21 -0
  166. basic_memory/services/file_service.py +402 -33
  167. basic_memory/services/initialization.py +216 -0
  168. basic_memory/services/link_resolver.py +50 -56
  169. basic_memory/services/project_service.py +888 -0
  170. basic_memory/services/search_service.py +232 -37
  171. basic_memory/sync/__init__.py +4 -2
  172. basic_memory/sync/background_sync.py +26 -0
  173. basic_memory/sync/coordinator.py +160 -0
  174. basic_memory/sync/sync_service.py +1200 -109
  175. basic_memory/sync/watch_service.py +432 -135
  176. basic_memory/telemetry.py +249 -0
  177. basic_memory/templates/prompts/continue_conversation.hbs +110 -0
  178. basic_memory/templates/prompts/search.hbs +101 -0
  179. basic_memory/utils.py +407 -54
  180. basic_memory-0.17.4.dist-info/METADATA +617 -0
  181. basic_memory-0.17.4.dist-info/RECORD +193 -0
  182. {basic_memory-0.7.0.dist-info → basic_memory-0.17.4.dist-info}/WHEEL +1 -1
  183. {basic_memory-0.7.0.dist-info → basic_memory-0.17.4.dist-info}/entry_points.txt +1 -0
  184. basic_memory/alembic/README +0 -1
  185. basic_memory/cli/commands/sync.py +0 -206
  186. basic_memory/cli/commands/tools.py +0 -157
  187. basic_memory/mcp/tools/knowledge.py +0 -68
  188. basic_memory/mcp/tools/memory.py +0 -170
  189. basic_memory/mcp/tools/notes.py +0 -202
  190. basic_memory/schemas/discovery.py +0 -28
  191. basic_memory/sync/file_change_scanner.py +0 -158
  192. basic_memory/sync/utils.py +0 -31
  193. basic_memory-0.7.0.dist-info/METADATA +0 -378
  194. basic_memory-0.7.0.dist-info/RECORD +0 -82
  195. {basic_memory-0.7.0.dist-info → basic_memory-0.17.4.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,888 @@
1
+ """Project management service for Basic Memory."""
2
+
3
+ import asyncio
4
+ import json
5
+ import os
6
+ import shutil
7
+ from datetime import datetime
8
+ from pathlib import Path
9
+ from typing import Dict, Optional, Sequence
10
+
11
+
12
+ from loguru import logger
13
+ from sqlalchemy import text
14
+
15
+ from basic_memory.models import Project
16
+ from basic_memory.repository.project_repository import ProjectRepository
17
+ from basic_memory.schemas import (
18
+ ActivityMetrics,
19
+ ProjectInfoResponse,
20
+ ProjectStatistics,
21
+ SystemStatus,
22
+ )
23
+ from basic_memory.config import WATCH_STATUS_JSON, ConfigManager, get_project_config, ProjectConfig
24
+ from basic_memory.utils import generate_permalink
25
+
26
+
27
+ class ProjectService:
28
+ """Service for managing Basic Memory projects."""
29
+
30
+ repository: ProjectRepository
31
+
32
+ def __init__(self, repository: ProjectRepository):
33
+ """Initialize the project service."""
34
+ super().__init__()
35
+ self.repository = repository
36
+
37
+ @property
38
+ def config_manager(self) -> ConfigManager:
39
+ """Get a ConfigManager instance.
40
+
41
+ Returns:
42
+ Fresh ConfigManager instance for each access
43
+ """
44
+ return ConfigManager()
45
+
46
+ @property
47
+ def config(self) -> ProjectConfig: # pragma: no cover
48
+ """Get the current project configuration.
49
+
50
+ Returns:
51
+ Current project configuration
52
+ """
53
+ return get_project_config()
54
+
55
+ @property
56
+ def projects(self) -> Dict[str, str]:
57
+ """Get all configured projects.
58
+
59
+ Returns:
60
+ Dict mapping project names to their file paths
61
+ """
62
+ return self.config_manager.projects
63
+
64
+ @property
65
+ def default_project(self) -> str:
66
+ """Get the name of the default project.
67
+
68
+ Returns:
69
+ The name of the default project
70
+ """
71
+ return self.config_manager.default_project
72
+
73
+ @property
74
+ def current_project(self) -> str:
75
+ """Get the name of the currently active project.
76
+
77
+ Returns:
78
+ The name of the current project
79
+ """
80
+ return os.environ.get("BASIC_MEMORY_PROJECT", self.config_manager.default_project)
81
+
82
+ async def list_projects(self) -> Sequence[Project]:
83
+ """List all projects without loading entity relationships.
84
+
85
+ Returns only basic project fields (name, path, etc.) without
86
+ eager loading the entities relationship which could load thousands
87
+ of entities for large knowledge bases.
88
+ """
89
+ return await self.repository.find_all(use_load_options=False)
90
+
91
+ async def get_project(self, name: str) -> Optional[Project]:
92
+ """Get the file path for a project by name or permalink."""
93
+ return await self.repository.get_by_name(name) or await self.repository.get_by_permalink(
94
+ name
95
+ )
96
+
97
+ def _check_nested_paths(self, path1: str, path2: str) -> bool:
98
+ """Check if two paths are nested (one is a prefix of the other).
99
+
100
+ Args:
101
+ path1: First path to compare
102
+ path2: Second path to compare
103
+
104
+ Returns:
105
+ True if one path is nested within the other, False otherwise
106
+
107
+ Examples:
108
+ _check_nested_paths("/foo", "/foo/bar") # True (child under parent)
109
+ _check_nested_paths("/foo/bar", "/foo") # True (parent over child)
110
+ _check_nested_paths("/foo", "/bar") # False (siblings)
111
+ """
112
+ # Normalize paths to ensure proper comparison
113
+ p1 = Path(path1).resolve()
114
+ p2 = Path(path2).resolve()
115
+
116
+ # Check if either path is a parent of the other
117
+ try:
118
+ # Check if p2 is under p1
119
+ p2.relative_to(p1)
120
+ return True
121
+ except ValueError:
122
+ # Not nested in this direction, check the other
123
+ try:
124
+ # Check if p1 is under p2
125
+ p1.relative_to(p2)
126
+ return True
127
+ except ValueError:
128
+ # Not nested in either direction
129
+ return False
130
+
131
+ async def add_project(self, name: str, path: str, set_default: bool = False) -> None:
132
+ """Add a new project to the configuration and database.
133
+
134
+ Args:
135
+ name: The name of the project
136
+ path: The file path to the project directory
137
+ set_default: Whether to set this project as the default
138
+
139
+ Raises:
140
+ ValueError: If the project already exists or path collides with existing project
141
+ """
142
+ # If project_root is set, constrain all projects to that directory
143
+ project_root = self.config_manager.config.project_root
144
+ sanitized_name = None
145
+ if project_root:
146
+ base_path = Path(project_root)
147
+
148
+ # In cloud mode (when project_root is set), ignore user's path completely
149
+ # and use sanitized project name as the directory name
150
+ # This ensures flat structure: /app/data/test-bisync instead of /app/data/documents/test bisync
151
+ sanitized_name = generate_permalink(name)
152
+
153
+ # Construct path using sanitized project name only
154
+ resolved_path = (base_path / sanitized_name).resolve().as_posix()
155
+
156
+ # Verify the resolved path is actually under project_root
157
+ if not resolved_path.startswith(base_path.resolve().as_posix()): # pragma: no cover
158
+ raise ValueError(
159
+ f"BASIC_MEMORY_PROJECT_ROOT is set to {project_root}. "
160
+ f"All projects must be created under this directory. Invalid path: {path}"
161
+ ) # pragma: no cover
162
+
163
+ # Check for case-insensitive path collisions with existing projects
164
+ existing_projects = await self.list_projects()
165
+ for existing in existing_projects:
166
+ if (
167
+ existing.path.lower() == resolved_path.lower()
168
+ and existing.path != resolved_path
169
+ ):
170
+ raise ValueError( # pragma: no cover
171
+ f"Path collision detected: '{resolved_path}' conflicts with existing project "
172
+ f"'{existing.name}' at '{existing.path}'. "
173
+ f"In cloud mode, paths are normalized to lowercase to prevent case-sensitivity issues."
174
+ ) # pragma: no cover
175
+ else:
176
+ resolved_path = Path(os.path.abspath(os.path.expanduser(path))).as_posix()
177
+
178
+ # Check for nested paths with existing projects
179
+ existing_projects = await self.list_projects()
180
+ for existing in existing_projects:
181
+ if self._check_nested_paths(resolved_path, existing.path):
182
+ # Determine which path is nested within which for appropriate error message
183
+ p_new = Path(resolved_path).resolve()
184
+ p_existing = Path(existing.path).resolve()
185
+
186
+ # Check if new path is nested under existing project
187
+ if p_new.is_relative_to(p_existing):
188
+ raise ValueError(
189
+ f"Cannot create project at '{resolved_path}': "
190
+ f"path is nested within existing project '{existing.name}' at '{existing.path}'. "
191
+ f"Projects cannot share directory trees."
192
+ )
193
+ else:
194
+ # Existing project is nested under new path
195
+ raise ValueError(
196
+ f"Cannot create project at '{resolved_path}': "
197
+ f"existing project '{existing.name}' at '{existing.path}' is nested within this path. "
198
+ f"Projects cannot share directory trees."
199
+ )
200
+
201
+ if not self.config_manager.config.cloud_mode:
202
+ # First add to config file (this will validate the project doesn't exist)
203
+ self.config_manager.add_project(name, resolved_path)
204
+
205
+ # Then add to database
206
+ project_data = {
207
+ "name": name,
208
+ "path": resolved_path,
209
+ "permalink": sanitized_name,
210
+ "is_active": True,
211
+ # Don't set is_default=False to avoid UNIQUE constraint issues
212
+ # Let it default to NULL, only set to True when explicitly making default
213
+ }
214
+ created_project = await self.repository.create(project_data)
215
+
216
+ # If this should be the default project, ensure only one default exists
217
+ if set_default:
218
+ await self.repository.set_as_default(created_project.id)
219
+ self.config_manager.set_default_project(name)
220
+ logger.info(f"Project '{name}' set as default")
221
+
222
+ logger.info(f"Project '{name}' added at {resolved_path}")
223
+
224
+ async def remove_project(self, name: str, delete_notes: bool = False) -> None:
225
+ """Remove a project from configuration and database.
226
+
227
+ Args:
228
+ name: The name of the project to remove
229
+ delete_notes: If True, delete the project directory from filesystem
230
+
231
+ Raises:
232
+ ValueError: If the project doesn't exist or is the default project
233
+ """
234
+ if not self.repository: # pragma: no cover
235
+ raise ValueError("Repository is required for remove_project")
236
+
237
+ # Get project from database first
238
+ project = await self.get_project(name)
239
+ if not project:
240
+ raise ValueError(f"Project '{name}' not found") # pragma: no cover
241
+
242
+ project_path = project.path
243
+
244
+ # Check if project is default (in cloud mode, check database; in local mode, check config)
245
+ if project.is_default or name == self.config_manager.config.default_project:
246
+ raise ValueError(f"Cannot remove the default project '{name}'") # pragma: no cover
247
+
248
+ # Remove from config if it exists there (may not exist in cloud mode)
249
+ try:
250
+ self.config_manager.remove_project(name)
251
+ except ValueError: # pragma: no cover
252
+ # Project not in config - that's OK in cloud mode, continue with database deletion
253
+ logger.debug( # pragma: no cover
254
+ f"Project '{name}' not found in config, removing from database only"
255
+ )
256
+
257
+ # Remove from database
258
+ await self.repository.delete(project.id)
259
+
260
+ logger.info(f"Project '{name}' removed from configuration and database")
261
+
262
+ # Optionally delete the project directory
263
+ if delete_notes and project_path:
264
+ try:
265
+ path_obj = Path(project_path)
266
+ if path_obj.exists() and path_obj.is_dir():
267
+ await asyncio.to_thread(shutil.rmtree, project_path)
268
+ logger.info(f"Deleted project directory: {project_path}")
269
+ else:
270
+ logger.warning( # pragma: no cover
271
+ f"Project directory not found or not a directory: {project_path}"
272
+ ) # pragma: no cover
273
+ except Exception as e: # pragma: no cover
274
+ logger.warning( # pragma: no cover
275
+ f"Failed to delete project directory {project_path}: {e}"
276
+ )
277
+
278
+ async def set_default_project(self, name: str) -> None:
279
+ """Set the default project in configuration and database.
280
+
281
+ Args:
282
+ name: The name of the project to set as default
283
+
284
+ Raises:
285
+ ValueError: If the project doesn't exist
286
+ """
287
+ if not self.repository: # pragma: no cover
288
+ raise ValueError("Repository is required for set_default_project")
289
+
290
+ # Look up project in database first to validate it exists
291
+ project = await self.get_project(name)
292
+ if not project:
293
+ raise ValueError(f"Project '{name}' not found")
294
+
295
+ # Update database
296
+ await self.repository.set_as_default(project.id)
297
+
298
+ # Update config file only in local mode (cloud mode uses database only)
299
+ if not self.config_manager.config.cloud_mode:
300
+ self.config_manager.set_default_project(name)
301
+
302
+ logger.info(f"Project '{name}' set as default in configuration and database")
303
+
304
+ async def _ensure_single_default_project(self) -> None:
305
+ """Ensure only one project has is_default=True.
306
+
307
+ This method validates the database state and fixes any issues where
308
+ multiple projects might have is_default=True or no project is marked as default.
309
+ """
310
+ if not self.repository:
311
+ raise ValueError(
312
+ "Repository is required for _ensure_single_default_project"
313
+ ) # pragma: no cover
314
+
315
+ # Get all projects with is_default=True
316
+ db_projects = await self.repository.find_all()
317
+ default_projects = [p for p in db_projects if p.is_default is True]
318
+
319
+ if len(default_projects) > 1: # pragma: no cover
320
+ # Multiple defaults found - fix by keeping the first one and clearing others
321
+ # This is defensive code that should rarely execute due to business logic enforcement
322
+ logger.warning( # pragma: no cover
323
+ f"Found {len(default_projects)} projects with is_default=True, fixing..."
324
+ )
325
+ keep_default = default_projects[0] # pragma: no cover
326
+
327
+ # Clear all defaults first, then set only the first one as default
328
+ await self.repository.set_as_default(keep_default.id) # pragma: no cover
329
+
330
+ logger.info(
331
+ f"Fixed default project conflicts, kept '{keep_default.name}' as default"
332
+ ) # pragma: no cover
333
+
334
+ elif len(default_projects) == 0: # pragma: no cover
335
+ # No default project - set the config default as default
336
+ # This is defensive code for edge cases where no default exists
337
+ config_default = self.config_manager.default_project # pragma: no cover
338
+ config_project = await self.repository.get_by_name(config_default) # pragma: no cover
339
+ if config_project: # pragma: no cover
340
+ await self.repository.set_as_default(config_project.id) # pragma: no cover
341
+ logger.info(
342
+ f"Set '{config_default}' as default project (was missing)"
343
+ ) # pragma: no cover
344
+
345
+ async def synchronize_projects(self) -> None: # pragma: no cover
346
+ """Synchronize projects between database and configuration.
347
+
348
+ Ensures that all projects in the configuration file exist in the database
349
+ and vice versa. This should be called during initialization to reconcile
350
+ any differences between the two sources.
351
+ """
352
+ if not self.repository:
353
+ raise ValueError("Repository is required for synchronize_projects")
354
+
355
+ logger.info("Synchronizing projects between database and configuration")
356
+
357
+ # Get all projects from database
358
+ db_projects = await self.repository.get_active_projects()
359
+ db_projects_by_permalink = {p.permalink: p for p in db_projects}
360
+
361
+ # Get all projects from configuration and normalize names if needed
362
+ config_projects = self.config_manager.projects.copy()
363
+ updated_config = {}
364
+ config_updated = False
365
+
366
+ for name, path in config_projects.items():
367
+ # Generate normalized name (what the database expects)
368
+ normalized_name = generate_permalink(name)
369
+
370
+ if normalized_name != name:
371
+ logger.info(f"Normalizing project name in config: '{name}' -> '{normalized_name}'")
372
+ config_updated = True
373
+
374
+ updated_config[normalized_name] = path
375
+
376
+ # Update the configuration if any changes were made
377
+ if config_updated:
378
+ config = self.config_manager.load_config()
379
+ config.projects = updated_config
380
+ self.config_manager.save_config(config)
381
+ logger.info("Config updated with normalized project names")
382
+
383
+ # Use the normalized config for further processing
384
+ config_projects = updated_config
385
+
386
+ # Add projects that exist in config but not in DB
387
+ for name, path in config_projects.items():
388
+ if name not in db_projects_by_permalink:
389
+ logger.info(f"Adding project '{name}' to database")
390
+ project_data = {
391
+ "name": name,
392
+ "path": path,
393
+ "permalink": generate_permalink(name),
394
+ "is_active": True,
395
+ # Don't set is_default here - let the enforcement logic handle it
396
+ }
397
+ await self.repository.create(project_data)
398
+
399
+ # Remove projects that exist in DB but not in config
400
+ # Config is the source of truth - if a project was deleted from config,
401
+ # it should be deleted from DB too (fixes issue #193)
402
+ for name, project in db_projects_by_permalink.items():
403
+ if name not in config_projects:
404
+ logger.info(
405
+ f"Removing project '{name}' from database (deleted from config, source of truth)"
406
+ )
407
+ await self.repository.delete(project.id)
408
+
409
+ # Ensure database default project state is consistent
410
+ await self._ensure_single_default_project()
411
+
412
+ # Make sure default project is synchronized between config and database
413
+ db_default = await self.repository.get_default_project()
414
+ config_default = self.config_manager.default_project
415
+
416
+ if db_default and db_default.name != config_default:
417
+ # Update config to match DB default
418
+ logger.info(f"Updating default project in config to '{db_default.name}'")
419
+ self.config_manager.set_default_project(db_default.name)
420
+ elif not db_default and config_default:
421
+ # Update DB to match config default (if the project exists)
422
+ project = await self.repository.get_by_name(config_default)
423
+ if project:
424
+ logger.info(f"Updating default project in database to '{config_default}'")
425
+ await self.repository.set_as_default(project.id)
426
+
427
+ logger.info("Project synchronization complete")
428
+
429
+ async def move_project(self, name: str, new_path: str) -> None:
430
+ """Move a project to a new location.
431
+
432
+ Args:
433
+ name: The name of the project to move
434
+ new_path: The new absolute path for the project
435
+
436
+ Raises:
437
+ ValueError: If the project doesn't exist or repository isn't initialized
438
+ """
439
+ if not self.repository: # pragma: no cover
440
+ raise ValueError("Repository is required for move_project") # pragma: no cover
441
+
442
+ # Resolve to absolute path
443
+ resolved_path = Path(os.path.abspath(os.path.expanduser(new_path))).as_posix()
444
+
445
+ # Validate project exists in config
446
+ if name not in self.config_manager.projects:
447
+ raise ValueError(f"Project '{name}' not found in configuration")
448
+
449
+ # Create the new directory if it doesn't exist
450
+ Path(resolved_path).mkdir(parents=True, exist_ok=True)
451
+
452
+ # Update in configuration
453
+ config = self.config_manager.load_config()
454
+ old_path = config.projects[name]
455
+ config.projects[name] = resolved_path
456
+ self.config_manager.save_config(config)
457
+
458
+ # Update in database using robust lookup
459
+ project = await self.get_project(name)
460
+ if project:
461
+ await self.repository.update_path(project.id, resolved_path)
462
+ logger.info(f"Moved project '{name}' from {old_path} to {resolved_path}")
463
+ else:
464
+ logger.error(f"Project '{name}' exists in config but not in database")
465
+ # Restore the old path in config since DB update failed
466
+ config.projects[name] = old_path
467
+ self.config_manager.save_config(config)
468
+ raise ValueError(f"Project '{name}' not found in database")
469
+
470
+ async def update_project( # pragma: no cover
471
+ self, name: str, updated_path: Optional[str] = None, is_active: Optional[bool] = None
472
+ ) -> None:
473
+ """Update project information in both config and database.
474
+
475
+ Args:
476
+ name: The name of the project to update
477
+ updated_path: Optional new path for the project
478
+ is_active: Optional flag to set project active status
479
+
480
+ Raises:
481
+ ValueError: If project doesn't exist or repository isn't initialized
482
+ """
483
+ if not self.repository:
484
+ raise ValueError("Repository is required for update_project")
485
+
486
+ # Validate project exists in config
487
+ if name not in self.config_manager.projects:
488
+ raise ValueError(f"Project '{name}' not found in configuration")
489
+
490
+ # Get project from database using robust lookup
491
+ project = await self.get_project(name)
492
+ if not project:
493
+ logger.error(f"Project '{name}' exists in config but not in database")
494
+ return
495
+
496
+ # Update path if provided
497
+ if updated_path:
498
+ resolved_path = Path(os.path.abspath(os.path.expanduser(updated_path))).as_posix()
499
+
500
+ # Update in config
501
+ config = self.config_manager.load_config()
502
+ config.projects[name] = resolved_path
503
+ self.config_manager.save_config(config)
504
+
505
+ # Update in database
506
+ project.path = resolved_path
507
+ await self.repository.update(project.id, project)
508
+
509
+ logger.info(f"Updated path for project '{name}' to {resolved_path}")
510
+
511
+ # Update active status if provided
512
+ if is_active is not None:
513
+ project.is_active = is_active
514
+ await self.repository.update(project.id, project)
515
+ logger.info(f"Set active status for project '{name}' to {is_active}")
516
+
517
+ # If project was made inactive and it was the default, we need to pick a new default
518
+ if is_active is False and project.is_default:
519
+ # Find another active project
520
+ active_projects = await self.repository.get_active_projects()
521
+ if active_projects:
522
+ new_default = active_projects[0]
523
+ await self.repository.set_as_default(new_default.id)
524
+ self.config_manager.set_default_project(new_default.name)
525
+ logger.info(
526
+ f"Changed default project to '{new_default.name}' as '{name}' was deactivated"
527
+ )
528
+
529
+ async def get_project_info(self, project_name: Optional[str] = None) -> ProjectInfoResponse:
530
+ """Get comprehensive information about the specified Basic Memory project.
531
+
532
+ Args:
533
+ project_name: Name of the project to get info for. If None, uses the current config project.
534
+
535
+ Returns:
536
+ Comprehensive project information and statistics
537
+ """
538
+ if not self.repository: # pragma: no cover
539
+ raise ValueError("Repository is required for get_project_info")
540
+
541
+ # Use specified project or fall back to config project
542
+ project_name = project_name or self.config.project
543
+ # Get project path from configuration
544
+ name, project_path = self.config_manager.get_project(project_name)
545
+ if not name: # pragma: no cover
546
+ raise ValueError(f"Project '{project_name}' not found in configuration")
547
+
548
+ assert project_path is not None
549
+ project_permalink = generate_permalink(project_name)
550
+
551
+ # Get project from database to get project_id
552
+ db_project = await self.repository.get_by_permalink(project_permalink)
553
+ if not db_project: # pragma: no cover
554
+ raise ValueError(f"Project '{project_name}' not found in database")
555
+
556
+ # Get statistics for the specified project
557
+ statistics = await self.get_statistics(db_project.id)
558
+
559
+ # Get activity metrics for the specified project
560
+ activity = await self.get_activity_metrics(db_project.id)
561
+
562
+ # Get system status
563
+ system = self.get_system_status()
564
+
565
+ # Get enhanced project information from database
566
+ db_projects = await self.repository.get_active_projects()
567
+ db_projects_by_permalink = {p.permalink: p for p in db_projects}
568
+
569
+ # Get default project info
570
+ default_project = self.config_manager.default_project
571
+
572
+ # Convert config projects to include database info
573
+ enhanced_projects = {}
574
+ for name, path in self.config_manager.projects.items():
575
+ config_permalink = generate_permalink(name)
576
+ db_project = db_projects_by_permalink.get(config_permalink)
577
+ enhanced_projects[name] = {
578
+ "path": path,
579
+ "active": db_project.is_active if db_project else True,
580
+ "id": db_project.id if db_project else None,
581
+ "is_default": (name == default_project),
582
+ "permalink": db_project.permalink if db_project else name.lower().replace(" ", "-"),
583
+ }
584
+
585
+ # Construct the response
586
+ return ProjectInfoResponse(
587
+ project_name=project_name,
588
+ project_path=project_path,
589
+ available_projects=enhanced_projects,
590
+ default_project=default_project,
591
+ statistics=statistics,
592
+ activity=activity,
593
+ system=system,
594
+ )
595
+
596
+ async def get_statistics(self, project_id: int) -> ProjectStatistics:
597
+ """Get statistics about the specified project.
598
+
599
+ Args:
600
+ project_id: ID of the project to get statistics for (required).
601
+ """
602
+ if not self.repository: # pragma: no cover
603
+ raise ValueError("Repository is required for get_statistics")
604
+
605
+ # Get basic counts
606
+ entity_count_result = await self.repository.execute_query(
607
+ text("SELECT COUNT(*) FROM entity WHERE project_id = :project_id"),
608
+ {"project_id": project_id},
609
+ )
610
+ total_entities = entity_count_result.scalar() or 0
611
+
612
+ observation_count_result = await self.repository.execute_query(
613
+ text(
614
+ "SELECT COUNT(*) FROM observation o JOIN entity e ON o.entity_id = e.id WHERE e.project_id = :project_id"
615
+ ),
616
+ {"project_id": project_id},
617
+ )
618
+ total_observations = observation_count_result.scalar() or 0
619
+
620
+ relation_count_result = await self.repository.execute_query(
621
+ text(
622
+ "SELECT COUNT(*) FROM relation r JOIN entity e ON r.from_id = e.id WHERE e.project_id = :project_id"
623
+ ),
624
+ {"project_id": project_id},
625
+ )
626
+ total_relations = relation_count_result.scalar() or 0
627
+
628
+ unresolved_count_result = await self.repository.execute_query(
629
+ text(
630
+ "SELECT COUNT(*) FROM relation r JOIN entity e ON r.from_id = e.id WHERE r.to_id IS NULL AND e.project_id = :project_id"
631
+ ),
632
+ {"project_id": project_id},
633
+ )
634
+ total_unresolved = unresolved_count_result.scalar() or 0
635
+
636
+ # Get entity counts by type
637
+ entity_types_result = await self.repository.execute_query(
638
+ text(
639
+ "SELECT entity_type, COUNT(*) FROM entity WHERE project_id = :project_id GROUP BY entity_type"
640
+ ),
641
+ {"project_id": project_id},
642
+ )
643
+ entity_types = {row[0]: row[1] for row in entity_types_result.fetchall()}
644
+
645
+ # Get observation counts by category
646
+ category_result = await self.repository.execute_query(
647
+ text(
648
+ "SELECT o.category, COUNT(*) FROM observation o JOIN entity e ON o.entity_id = e.id WHERE e.project_id = :project_id GROUP BY o.category"
649
+ ),
650
+ {"project_id": project_id},
651
+ )
652
+ observation_categories = {row[0]: row[1] for row in category_result.fetchall()}
653
+
654
+ # Get relation counts by type
655
+ relation_types_result = await self.repository.execute_query(
656
+ text(
657
+ "SELECT r.relation_type, COUNT(*) FROM relation r JOIN entity e ON r.from_id = e.id WHERE e.project_id = :project_id GROUP BY r.relation_type"
658
+ ),
659
+ {"project_id": project_id},
660
+ )
661
+ relation_types = {row[0]: row[1] for row in relation_types_result.fetchall()}
662
+
663
+ # Find most connected entities (most outgoing relations) - project filtered
664
+ connected_result = await self.repository.execute_query(
665
+ text("""
666
+ SELECT e.id, e.title, e.permalink, COUNT(r.id) AS relation_count, e.file_path
667
+ FROM entity e
668
+ JOIN relation r ON e.id = r.from_id
669
+ WHERE e.project_id = :project_id
670
+ GROUP BY e.id
671
+ ORDER BY relation_count DESC
672
+ LIMIT 10
673
+ """),
674
+ {"project_id": project_id},
675
+ )
676
+ most_connected = [
677
+ {
678
+ "id": row[0],
679
+ "title": row[1],
680
+ "permalink": row[2],
681
+ "relation_count": row[3],
682
+ "file_path": row[4],
683
+ }
684
+ for row in connected_result.fetchall()
685
+ ]
686
+
687
+ # Count isolated entities (no relations) - project filtered
688
+ isolated_result = await self.repository.execute_query(
689
+ text("""
690
+ SELECT COUNT(e.id)
691
+ FROM entity e
692
+ LEFT JOIN relation r1 ON e.id = r1.from_id
693
+ LEFT JOIN relation r2 ON e.id = r2.to_id
694
+ WHERE e.project_id = :project_id AND r1.id IS NULL AND r2.id IS NULL
695
+ """),
696
+ {"project_id": project_id},
697
+ )
698
+ isolated_count = isolated_result.scalar() or 0
699
+
700
+ return ProjectStatistics(
701
+ total_entities=total_entities,
702
+ total_observations=total_observations,
703
+ total_relations=total_relations,
704
+ total_unresolved_relations=total_unresolved,
705
+ entity_types=entity_types,
706
+ observation_categories=observation_categories,
707
+ relation_types=relation_types,
708
+ most_connected_entities=most_connected,
709
+ isolated_entities=isolated_count,
710
+ )
711
+
712
+ async def get_activity_metrics(self, project_id: int) -> ActivityMetrics:
713
+ """Get activity metrics for the specified project.
714
+
715
+ Args:
716
+ project_id: ID of the project to get activity metrics for (required).
717
+ """
718
+ if not self.repository: # pragma: no cover
719
+ raise ValueError("Repository is required for get_activity_metrics")
720
+
721
+ # Get recently created entities (project filtered)
722
+ created_result = await self.repository.execute_query(
723
+ text("""
724
+ SELECT id, title, permalink, entity_type, created_at, file_path
725
+ FROM entity
726
+ WHERE project_id = :project_id
727
+ ORDER BY created_at DESC
728
+ LIMIT 10
729
+ """),
730
+ {"project_id": project_id},
731
+ )
732
+ recently_created = [
733
+ {
734
+ "id": row[0],
735
+ "title": row[1],
736
+ "permalink": row[2],
737
+ "entity_type": row[3],
738
+ "created_at": row[4],
739
+ "file_path": row[5],
740
+ }
741
+ for row in created_result.fetchall()
742
+ ]
743
+
744
+ # Get recently updated entities (project filtered)
745
+ updated_result = await self.repository.execute_query(
746
+ text("""
747
+ SELECT id, title, permalink, entity_type, updated_at, file_path
748
+ FROM entity
749
+ WHERE project_id = :project_id
750
+ ORDER BY updated_at DESC
751
+ LIMIT 10
752
+ """),
753
+ {"project_id": project_id},
754
+ )
755
+ recently_updated = [
756
+ {
757
+ "id": row[0],
758
+ "title": row[1],
759
+ "permalink": row[2],
760
+ "entity_type": row[3],
761
+ "updated_at": row[4],
762
+ "file_path": row[5],
763
+ }
764
+ for row in updated_result.fetchall()
765
+ ]
766
+
767
+ # Get monthly growth over the last 6 months
768
+ # Calculate the start of 6 months ago
769
+ now = datetime.now()
770
+ six_months_ago = datetime(
771
+ now.year - (1 if now.month <= 6 else 0), ((now.month - 6) % 12) or 12, 1
772
+ )
773
+
774
+ # Query for monthly entity creation (project filtered)
775
+ # Use different date formatting for SQLite vs Postgres
776
+ from basic_memory.config import DatabaseBackend
777
+
778
+ is_postgres = self.config_manager.config.database_backend == DatabaseBackend.POSTGRES
779
+ date_format = (
780
+ "to_char(created_at, 'YYYY-MM')" if is_postgres else "strftime('%Y-%m', created_at)"
781
+ )
782
+
783
+ # Postgres needs datetime objects, SQLite needs ISO strings
784
+ six_months_param = six_months_ago if is_postgres else six_months_ago.isoformat()
785
+
786
+ entity_growth_result = await self.repository.execute_query(
787
+ text(f"""
788
+ SELECT
789
+ {date_format} AS month,
790
+ COUNT(*) AS count
791
+ FROM entity
792
+ WHERE created_at >= :six_months_ago AND project_id = :project_id
793
+ GROUP BY month
794
+ ORDER BY month
795
+ """),
796
+ {"six_months_ago": six_months_param, "project_id": project_id},
797
+ )
798
+ entity_growth = {row[0]: row[1] for row in entity_growth_result.fetchall()}
799
+
800
+ # Query for monthly observation creation (project filtered)
801
+ date_format_entity = (
802
+ "to_char(entity.created_at, 'YYYY-MM')"
803
+ if is_postgres
804
+ else "strftime('%Y-%m', entity.created_at)"
805
+ )
806
+
807
+ observation_growth_result = await self.repository.execute_query(
808
+ text(f"""
809
+ SELECT
810
+ {date_format_entity} AS month,
811
+ COUNT(*) AS count
812
+ FROM observation
813
+ INNER JOIN entity ON observation.entity_id = entity.id
814
+ WHERE entity.created_at >= :six_months_ago AND entity.project_id = :project_id
815
+ GROUP BY month
816
+ ORDER BY month
817
+ """),
818
+ {"six_months_ago": six_months_param, "project_id": project_id},
819
+ )
820
+ observation_growth = {row[0]: row[1] for row in observation_growth_result.fetchall()}
821
+
822
+ # Query for monthly relation creation (project filtered)
823
+ relation_growth_result = await self.repository.execute_query(
824
+ text(f"""
825
+ SELECT
826
+ {date_format_entity} AS month,
827
+ COUNT(*) AS count
828
+ FROM relation
829
+ INNER JOIN entity ON relation.from_id = entity.id
830
+ WHERE entity.created_at >= :six_months_ago AND entity.project_id = :project_id
831
+ GROUP BY month
832
+ ORDER BY month
833
+ """),
834
+ {"six_months_ago": six_months_param, "project_id": project_id},
835
+ )
836
+ relation_growth = {row[0]: row[1] for row in relation_growth_result.fetchall()}
837
+
838
+ # Combine all monthly growth data
839
+ monthly_growth = {}
840
+ for month in set(
841
+ list(entity_growth.keys())
842
+ + list(observation_growth.keys())
843
+ + list(relation_growth.keys())
844
+ ):
845
+ monthly_growth[month] = {
846
+ "entities": entity_growth.get(month, 0),
847
+ "observations": observation_growth.get(month, 0),
848
+ "relations": relation_growth.get(month, 0),
849
+ "total": (
850
+ entity_growth.get(month, 0)
851
+ + observation_growth.get(month, 0)
852
+ + relation_growth.get(month, 0)
853
+ ),
854
+ }
855
+
856
+ return ActivityMetrics(
857
+ recently_created=recently_created,
858
+ recently_updated=recently_updated,
859
+ monthly_growth=monthly_growth,
860
+ )
861
+
862
+ def get_system_status(self) -> SystemStatus:
863
+ """Get system status information."""
864
+ import basic_memory
865
+
866
+ # Get database information
867
+ db_path = self.config_manager.config.database_path
868
+ db_size = db_path.stat().st_size if db_path.exists() else 0
869
+ db_size_readable = f"{db_size / (1024 * 1024):.2f} MB"
870
+
871
+ # Get watch service status if available
872
+ watch_status = None
873
+ watch_status_path = Path.home() / ".basic-memory" / WATCH_STATUS_JSON
874
+ if watch_status_path.exists():
875
+ try: # pragma: no cover
876
+ watch_status = json.loads( # pragma: no cover
877
+ watch_status_path.read_text(encoding="utf-8")
878
+ )
879
+ except Exception: # pragma: no cover
880
+ pass
881
+
882
+ return SystemStatus(
883
+ version=basic_memory.__version__,
884
+ database_path=str(db_path),
885
+ database_size=db_size_readable,
886
+ watch_status=watch_status,
887
+ timestamp=datetime.now(),
888
+ )