basic-memory 0.2.12__py3-none-any.whl → 0.16.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.

Potentially problematic release.


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

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