basic-memory 0.7.0__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 (150) 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 +64 -18
  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 +166 -21
  18. basic_memory/api/routers/management_router.py +80 -0
  19. basic_memory/api/routers/memory_router.py +9 -64
  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 +119 -4
  23. basic_memory/api/routers/search_router.py +5 -5
  24. basic_memory/api/routers/utils.py +130 -0
  25. basic_memory/api/template_loader.py +292 -0
  26. basic_memory/cli/app.py +43 -9
  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 +28 -12
  41. basic_memory/cli/commands/import_chatgpt.py +40 -220
  42. basic_memory/cli/commands/import_claude_conversations.py +41 -168
  43. basic_memory/cli/commands/import_claude_projects.py +46 -157
  44. basic_memory/cli/commands/import_memory_json.py +48 -108
  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 +50 -33
  48. basic_memory/cli/commands/tool.py +341 -0
  49. basic_memory/cli/main.py +8 -7
  50. basic_memory/config.py +477 -23
  51. basic_memory/db.py +168 -17
  52. basic_memory/deps.py +251 -25
  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 -23
  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 +411 -62
  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 +187 -25
  112. basic_memory/schemas/project_info.py +211 -0
  113. basic_memory/schemas/prompt.py +90 -0
  114. basic_memory/schemas/request.py +56 -2
  115. basic_memory/schemas/response.py +1 -1
  116. basic_memory/schemas/search.py +31 -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 +241 -104
  120. basic_memory/services/directory_service.py +295 -0
  121. basic_memory/services/entity_service.py +590 -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 +49 -56
  126. basic_memory/services/project_service.py +863 -0
  127. basic_memory/services/search_service.py +168 -32
  128. basic_memory/sync/__init__.py +3 -2
  129. basic_memory/sync/background_sync.py +26 -0
  130. basic_memory/sync/sync_service.py +1180 -109
  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 +383 -51
  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.7.0.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 -206
  140. basic_memory/cli/commands/tools.py +0 -157
  141. basic_memory/mcp/tools/knowledge.py +0 -68
  142. basic_memory/mcp/tools/memory.py +0 -170
  143. basic_memory/mcp/tools/notes.py +0 -202
  144. basic_memory/schemas/discovery.py +0 -28
  145. basic_memory/sync/file_change_scanner.py +0 -158
  146. basic_memory/sync/utils.py +0 -31
  147. basic_memory-0.7.0.dist-info/METADATA +0 -378
  148. basic_memory-0.7.0.dist-info/RECORD +0 -82
  149. {basic_memory-0.7.0.dist-info → basic_memory-0.16.1.dist-info}/WHEEL +0 -0
  150. {basic_memory-0.7.0.dist-info → basic_memory-0.16.1.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,876 @@
1
+ """Command module for basic-memory project management."""
2
+
3
+ import asyncio
4
+ import os
5
+ from pathlib import Path
6
+
7
+ import typer
8
+ from rich.console import Console
9
+ from rich.table import Table
10
+
11
+ from basic_memory.cli.app import app
12
+ from basic_memory.cli.commands.command_utils import get_project_info
13
+ from basic_memory.config import ConfigManager
14
+ import json
15
+ from datetime import datetime
16
+
17
+ from rich.panel import Panel
18
+ from basic_memory.mcp.async_client import get_client
19
+ from basic_memory.mcp.tools.utils import call_get
20
+ from basic_memory.schemas.project_info import ProjectList
21
+ from basic_memory.mcp.tools.utils import call_post
22
+ from basic_memory.schemas.project_info import ProjectStatusResponse
23
+ from basic_memory.mcp.tools.utils import call_delete
24
+ from basic_memory.mcp.tools.utils import call_put
25
+ from basic_memory.utils import generate_permalink, normalize_project_path
26
+ from basic_memory.mcp.tools.utils import call_patch
27
+
28
+ # Import rclone commands for project sync
29
+ from basic_memory.cli.commands.cloud.rclone_commands import (
30
+ SyncProject,
31
+ RcloneError,
32
+ project_sync,
33
+ project_bisync,
34
+ project_check,
35
+ project_ls,
36
+ )
37
+ from basic_memory.cli.commands.cloud.bisync_commands import get_mount_info
38
+
39
+ console = Console()
40
+
41
+ # Create a project subcommand
42
+ project_app = typer.Typer(help="Manage multiple Basic Memory projects")
43
+ app.add_typer(project_app, name="project")
44
+
45
+
46
+ def format_path(path: str) -> str:
47
+ """Format a path for display, using ~ for home directory."""
48
+ home = str(Path.home())
49
+ if path.startswith(home):
50
+ return path.replace(home, "~", 1) # pragma: no cover
51
+ return path
52
+
53
+
54
+ @project_app.command("list")
55
+ def list_projects() -> None:
56
+ """List all Basic Memory projects."""
57
+
58
+ async def _list_projects():
59
+ async with get_client() as client:
60
+ response = await call_get(client, "/projects/projects")
61
+ return ProjectList.model_validate(response.json())
62
+
63
+ try:
64
+ result = asyncio.run(_list_projects())
65
+ config = ConfigManager().config
66
+
67
+ table = Table(title="Basic Memory Projects")
68
+ table.add_column("Name", style="cyan")
69
+ table.add_column("Path", style="green")
70
+
71
+ # Add Local Path column if in cloud mode
72
+ if config.cloud_mode_enabled:
73
+ table.add_column("Local Path", style="yellow", no_wrap=True, overflow="fold")
74
+
75
+ # Show Default column in local mode or if default_project_mode is enabled in cloud mode
76
+ show_default_column = not config.cloud_mode_enabled or config.default_project_mode
77
+ if show_default_column:
78
+ table.add_column("Default", style="magenta")
79
+
80
+ for project in result.projects:
81
+ is_default = "[X]" if project.is_default else ""
82
+ normalized_path = normalize_project_path(project.path)
83
+
84
+ # Build row based on mode
85
+ row = [project.name, format_path(normalized_path)]
86
+
87
+ # Add local path if in cloud mode
88
+ if config.cloud_mode_enabled:
89
+ local_path = ""
90
+ if project.name in config.cloud_projects:
91
+ local_path = config.cloud_projects[project.name].local_path or ""
92
+ local_path = format_path(local_path)
93
+ row.append(local_path)
94
+
95
+ # Add default indicator if showing default column
96
+ if show_default_column:
97
+ row.append(is_default)
98
+
99
+ table.add_row(*row)
100
+
101
+ console.print(table)
102
+ except Exception as e:
103
+ console.print(f"[red]Error listing projects: {str(e)}[/red]")
104
+ raise typer.Exit(1)
105
+
106
+
107
+ @project_app.command("add")
108
+ def add_project(
109
+ name: str = typer.Argument(..., help="Name of the project"),
110
+ path: str = typer.Argument(
111
+ None, help="Path to the project directory (required for local mode)"
112
+ ),
113
+ local_path: str = typer.Option(
114
+ None, "--local-path", help="Local sync path for cloud mode (optional)"
115
+ ),
116
+ set_default: bool = typer.Option(False, "--default", help="Set as default project"),
117
+ ) -> None:
118
+ """Add a new project.
119
+
120
+ Cloud mode examples:\n
121
+ bm project add research # No local sync\n
122
+ bm project add research --local-path ~/docs # With local sync\n
123
+
124
+ Local mode example:\n
125
+ bm project add research ~/Documents/research
126
+ """
127
+ config = ConfigManager().config
128
+
129
+ # Resolve local sync path early (needed for both cloud and local mode)
130
+ local_sync_path: str | None = None
131
+ if local_path:
132
+ local_sync_path = Path(os.path.abspath(os.path.expanduser(local_path))).as_posix()
133
+
134
+ if config.cloud_mode_enabled:
135
+ # Cloud mode: path auto-generated from name, local sync is optional
136
+
137
+ async def _add_project():
138
+ async with get_client() as client:
139
+ data = {
140
+ "name": name,
141
+ "path": generate_permalink(name),
142
+ "local_sync_path": local_sync_path,
143
+ "set_default": set_default,
144
+ }
145
+ response = await call_post(client, "/projects/projects", json=data)
146
+ return ProjectStatusResponse.model_validate(response.json())
147
+ else:
148
+ # Local mode: path is required
149
+ if path is None:
150
+ console.print("[red]Error: path argument is required in local mode[/red]")
151
+ raise typer.Exit(1)
152
+
153
+ # Resolve to absolute path
154
+ resolved_path = Path(os.path.abspath(os.path.expanduser(path))).as_posix()
155
+
156
+ async def _add_project():
157
+ async with get_client() as client:
158
+ data = {"name": name, "path": resolved_path, "set_default": set_default}
159
+ response = await call_post(client, "/projects/projects", json=data)
160
+ return ProjectStatusResponse.model_validate(response.json())
161
+
162
+ try:
163
+ result = asyncio.run(_add_project())
164
+ console.print(f"[green]{result.message}[/green]")
165
+
166
+ # Save local sync path to config if in cloud mode
167
+ if config.cloud_mode_enabled and local_sync_path:
168
+ from basic_memory.config import CloudProjectConfig
169
+
170
+ # Create local directory if it doesn't exist
171
+ local_dir = Path(local_sync_path)
172
+ local_dir.mkdir(parents=True, exist_ok=True)
173
+
174
+ # Update config with sync path
175
+ config.cloud_projects[name] = CloudProjectConfig(
176
+ local_path=local_sync_path,
177
+ last_sync=None,
178
+ bisync_initialized=False,
179
+ )
180
+ ConfigManager().save_config(config)
181
+
182
+ console.print(f"\n[green]Local sync path configured: {local_sync_path}[/green]")
183
+ console.print("\nNext steps:")
184
+ console.print(f" 1. Preview: bm project bisync --name {name} --resync --dry-run")
185
+ console.print(f" 2. Sync: bm project bisync --name {name} --resync")
186
+ except Exception as e:
187
+ console.print(f"[red]Error adding project: {str(e)}[/red]")
188
+ raise typer.Exit(1)
189
+
190
+
191
+ @project_app.command("sync-setup")
192
+ def setup_project_sync(
193
+ name: str = typer.Argument(..., help="Project name"),
194
+ local_path: str = typer.Argument(..., help="Local sync directory"),
195
+ ) -> None:
196
+ """Configure local sync for an existing cloud project.
197
+
198
+ Example:
199
+ bm project sync-setup research ~/Documents/research
200
+ """
201
+ config_manager = ConfigManager()
202
+ config = config_manager.config
203
+
204
+ if not config.cloud_mode_enabled:
205
+ console.print("[red]Error: sync-setup only available in cloud mode[/red]")
206
+ raise typer.Exit(1)
207
+
208
+ async def _verify_project_exists():
209
+ """Verify the project exists on cloud by listing all projects."""
210
+ async with get_client() as client:
211
+ response = await call_get(client, "/projects/projects")
212
+ project_list = response.json()
213
+ project_names = [p["name"] for p in project_list["projects"]]
214
+ if name not in project_names:
215
+ raise ValueError(f"Project '{name}' not found on cloud")
216
+ return True
217
+
218
+ try:
219
+ # Verify project exists on cloud
220
+ asyncio.run(_verify_project_exists())
221
+
222
+ # Resolve and create local path
223
+ resolved_path = Path(os.path.abspath(os.path.expanduser(local_path)))
224
+ resolved_path.mkdir(parents=True, exist_ok=True)
225
+
226
+ # Update local config with sync path
227
+ from basic_memory.config import CloudProjectConfig
228
+
229
+ config.cloud_projects[name] = CloudProjectConfig(
230
+ local_path=resolved_path.as_posix(),
231
+ last_sync=None,
232
+ bisync_initialized=False,
233
+ )
234
+ config_manager.save_config(config)
235
+
236
+ console.print(f"[green]Sync configured for project '{name}'[/green]")
237
+ console.print(f"\nLocal sync path: {resolved_path}")
238
+ console.print("\nNext steps:")
239
+ console.print(f" 1. Preview: bm project bisync --name {name} --resync --dry-run")
240
+ console.print(f" 2. Sync: bm project bisync --name {name} --resync")
241
+ except Exception as e:
242
+ console.print(f"[red]Error configuring sync: {str(e)}[/red]")
243
+ raise typer.Exit(1)
244
+
245
+
246
+ @project_app.command("remove")
247
+ def remove_project(
248
+ name: str = typer.Argument(..., help="Name of the project to remove"),
249
+ delete_notes: bool = typer.Option(
250
+ False, "--delete-notes", help="Delete project files from disk"
251
+ ),
252
+ ) -> None:
253
+ """Remove a project."""
254
+
255
+ async def _remove_project():
256
+ async with get_client() as client:
257
+ project_permalink = generate_permalink(name)
258
+ response = await call_delete(
259
+ client, f"/projects/{project_permalink}?delete_notes={delete_notes}"
260
+ )
261
+ return ProjectStatusResponse.model_validate(response.json())
262
+
263
+ try:
264
+ # Get config to check for local sync path and bisync state
265
+ config = ConfigManager().config
266
+ local_path = None
267
+ has_bisync_state = False
268
+
269
+ if config.cloud_mode_enabled and name in config.cloud_projects:
270
+ local_path = config.cloud_projects[name].local_path
271
+
272
+ # Check for bisync state
273
+ from basic_memory.cli.commands.cloud.rclone_commands import get_project_bisync_state
274
+
275
+ bisync_state_path = get_project_bisync_state(name)
276
+ has_bisync_state = bisync_state_path.exists()
277
+
278
+ # Remove project from cloud/API
279
+ result = asyncio.run(_remove_project())
280
+ console.print(f"[green]{result.message}[/green]")
281
+
282
+ # Clean up local sync directory if it exists and delete_notes is True
283
+ if delete_notes and local_path:
284
+ local_dir = Path(local_path)
285
+ if local_dir.exists():
286
+ import shutil
287
+
288
+ shutil.rmtree(local_dir)
289
+ console.print(f"[green]Removed local sync directory: {local_path}[/green]")
290
+
291
+ # Clean up bisync state if it exists
292
+ if has_bisync_state:
293
+ from basic_memory.cli.commands.cloud.rclone_commands import get_project_bisync_state
294
+ import shutil
295
+
296
+ bisync_state_path = get_project_bisync_state(name)
297
+ if bisync_state_path.exists():
298
+ shutil.rmtree(bisync_state_path)
299
+ console.print("[green]Removed bisync state[/green]")
300
+
301
+ # Clean up cloud_projects config entry
302
+ if config.cloud_mode_enabled and name in config.cloud_projects:
303
+ del config.cloud_projects[name]
304
+ ConfigManager().save_config(config)
305
+
306
+ # Show informative message if files were not deleted
307
+ if not delete_notes:
308
+ if local_path:
309
+ console.print(f"[yellow]Note: Local files remain at {local_path}[/yellow]")
310
+
311
+ except Exception as e:
312
+ console.print(f"[red]Error removing project: {str(e)}[/red]")
313
+ raise typer.Exit(1)
314
+
315
+
316
+ @project_app.command("default")
317
+ def set_default_project(
318
+ name: str = typer.Argument(..., help="Name of the project to set as CLI default"),
319
+ ) -> None:
320
+ """Set the default project when 'config.default_project_mode' is set.
321
+
322
+ Note: This command is only available in local mode.
323
+ """
324
+ config = ConfigManager().config
325
+
326
+ if config.cloud_mode_enabled:
327
+ console.print("[red]Error: 'default' command is not available in cloud mode[/red]")
328
+ raise typer.Exit(1)
329
+
330
+ async def _set_default():
331
+ async with get_client() as client:
332
+ project_permalink = generate_permalink(name)
333
+ response = await call_put(client, f"/projects/{project_permalink}/default")
334
+ return ProjectStatusResponse.model_validate(response.json())
335
+
336
+ try:
337
+ result = asyncio.run(_set_default())
338
+ console.print(f"[green]{result.message}[/green]")
339
+ except Exception as e:
340
+ console.print(f"[red]Error setting default project: {str(e)}[/red]")
341
+ raise typer.Exit(1)
342
+
343
+
344
+ @project_app.command("sync-config")
345
+ def synchronize_projects() -> None:
346
+ """Synchronize project config between configuration file and database.
347
+
348
+ Note: This command is only available in local mode.
349
+ """
350
+ config = ConfigManager().config
351
+
352
+ if config.cloud_mode_enabled:
353
+ console.print("[red]Error: 'sync-config' command is not available in cloud mode[/red]")
354
+ raise typer.Exit(1)
355
+
356
+ async def _sync_config():
357
+ async with get_client() as client:
358
+ response = await call_post(client, "/projects/config/sync")
359
+ return ProjectStatusResponse.model_validate(response.json())
360
+
361
+ try:
362
+ result = asyncio.run(_sync_config())
363
+ console.print(f"[green]{result.message}[/green]")
364
+ except Exception as e: # pragma: no cover
365
+ console.print(f"[red]Error synchronizing projects: {str(e)}[/red]")
366
+ raise typer.Exit(1)
367
+
368
+
369
+ @project_app.command("move")
370
+ def move_project(
371
+ name: str = typer.Argument(..., help="Name of the project to move"),
372
+ new_path: str = typer.Argument(..., help="New absolute path for the project"),
373
+ ) -> None:
374
+ """Move a project to a new location.
375
+
376
+ Note: This command is only available in local mode.
377
+ """
378
+ config = ConfigManager().config
379
+
380
+ if config.cloud_mode_enabled:
381
+ console.print("[red]Error: 'move' command is not available in cloud mode[/red]")
382
+ raise typer.Exit(1)
383
+
384
+ # Resolve to absolute path
385
+ resolved_path = Path(os.path.abspath(os.path.expanduser(new_path))).as_posix()
386
+
387
+ async def _move_project():
388
+ async with get_client() as client:
389
+ data = {"path": resolved_path}
390
+ project_permalink = generate_permalink(name)
391
+
392
+ # TODO fix route to use ProjectPathDep
393
+ response = await call_patch(client, f"/{name}/project/{project_permalink}", json=data)
394
+ return ProjectStatusResponse.model_validate(response.json())
395
+
396
+ try:
397
+ result = asyncio.run(_move_project())
398
+ console.print(f"[green]{result.message}[/green]")
399
+
400
+ # Show important file movement reminder
401
+ console.print() # Empty line for spacing
402
+ console.print(
403
+ Panel(
404
+ "[bold red]IMPORTANT:[/bold red] Project configuration updated successfully.\n\n"
405
+ "[yellow]You must manually move your project files from the old location to:[/yellow]\n"
406
+ f"[cyan]{resolved_path}[/cyan]\n\n"
407
+ "[dim]Basic Memory has only updated the configuration - your files remain in their original location.[/dim]",
408
+ title="Manual File Movement Required",
409
+ border_style="yellow",
410
+ expand=False,
411
+ )
412
+ )
413
+
414
+ except Exception as e:
415
+ console.print(f"[red]Error moving project: {str(e)}[/red]")
416
+ raise typer.Exit(1)
417
+
418
+
419
+ @project_app.command("sync")
420
+ def sync_project_command(
421
+ name: str = typer.Option(..., "--name", help="Project name to sync"),
422
+ dry_run: bool = typer.Option(False, "--dry-run", help="Preview changes without syncing"),
423
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Show detailed output"),
424
+ ) -> None:
425
+ """One-way sync: local -> cloud (make cloud identical to local).
426
+
427
+ Example:
428
+ bm project sync --name research
429
+ bm project sync --name research --dry-run
430
+ """
431
+ config = ConfigManager().config
432
+ if not config.cloud_mode_enabled:
433
+ console.print("[red]Error: sync only available in cloud mode[/red]")
434
+ raise typer.Exit(1)
435
+
436
+ try:
437
+ # Get tenant info for bucket name
438
+ tenant_info = asyncio.run(get_mount_info())
439
+ bucket_name = tenant_info.bucket_name
440
+
441
+ # Get project info
442
+ async def _get_project():
443
+ async with get_client() as client:
444
+ response = await call_get(client, "/projects/projects")
445
+ projects_list = ProjectList.model_validate(response.json())
446
+ for proj in projects_list.projects:
447
+ if generate_permalink(proj.name) == generate_permalink(name):
448
+ return proj
449
+ return None
450
+
451
+ project_data = asyncio.run(_get_project())
452
+ if not project_data:
453
+ console.print(f"[red]Error: Project '{name}' not found[/red]")
454
+ raise typer.Exit(1)
455
+
456
+ # Get local_sync_path from cloud_projects config
457
+ local_sync_path = None
458
+ if name in config.cloud_projects:
459
+ local_sync_path = config.cloud_projects[name].local_path
460
+
461
+ if not local_sync_path:
462
+ console.print(f"[red]Error: Project '{name}' has no local_sync_path configured[/red]")
463
+ console.print(f"\nConfigure sync with: bm project sync-setup {name} ~/path/to/local")
464
+ raise typer.Exit(1)
465
+
466
+ # Create SyncProject
467
+ sync_project = SyncProject(
468
+ name=project_data.name,
469
+ path=normalize_project_path(project_data.path),
470
+ local_sync_path=local_sync_path,
471
+ )
472
+
473
+ # Run sync
474
+ console.print(f"[blue]Syncing {name} (local -> cloud)...[/blue]")
475
+ success = project_sync(sync_project, bucket_name, dry_run=dry_run, verbose=verbose)
476
+
477
+ if success:
478
+ console.print(f"[green]{name} synced successfully[/green]")
479
+
480
+ # Trigger database sync if not a dry run
481
+ if not dry_run:
482
+
483
+ async def _trigger_db_sync():
484
+ async with get_client() as client:
485
+ permalink = generate_permalink(name)
486
+ response = await call_post(
487
+ client, f"/{permalink}/project/sync?force_full=true", json={}
488
+ )
489
+ return response.json()
490
+
491
+ try:
492
+ result = asyncio.run(_trigger_db_sync())
493
+ console.print(f"[dim]Database sync initiated: {result.get('message')}[/dim]")
494
+ except Exception as e:
495
+ console.print(f"[yellow]Warning: Could not trigger database sync: {e}[/yellow]")
496
+ else:
497
+ console.print(f"[red]{name} sync failed[/red]")
498
+ raise typer.Exit(1)
499
+
500
+ except RcloneError as e:
501
+ console.print(f"[red]Sync error: {e}[/red]")
502
+ raise typer.Exit(1)
503
+ except Exception as e:
504
+ console.print(f"[red]Error: {e}[/red]")
505
+ raise typer.Exit(1)
506
+
507
+
508
+ @project_app.command("bisync")
509
+ def bisync_project_command(
510
+ name: str = typer.Option(..., "--name", help="Project name to bisync"),
511
+ dry_run: bool = typer.Option(False, "--dry-run", help="Preview changes without syncing"),
512
+ resync: bool = typer.Option(False, "--resync", help="Force new baseline"),
513
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Show detailed output"),
514
+ ) -> None:
515
+ """Two-way sync: local <-> cloud (bidirectional sync).
516
+
517
+ Examples:
518
+ bm project bisync --name research --resync # First time
519
+ bm project bisync --name research # Subsequent syncs
520
+ bm project bisync --name research --dry-run # Preview changes
521
+ """
522
+ config = ConfigManager().config
523
+ if not config.cloud_mode_enabled:
524
+ console.print("[red]Error: bisync only available in cloud mode[/red]")
525
+ raise typer.Exit(1)
526
+
527
+ try:
528
+ # Get tenant info for bucket name
529
+ tenant_info = asyncio.run(get_mount_info())
530
+ bucket_name = tenant_info.bucket_name
531
+
532
+ # Get project info
533
+ async def _get_project():
534
+ async with get_client() as client:
535
+ response = await call_get(client, "/projects/projects")
536
+ projects_list = ProjectList.model_validate(response.json())
537
+ for proj in projects_list.projects:
538
+ if generate_permalink(proj.name) == generate_permalink(name):
539
+ return proj
540
+ return None
541
+
542
+ project_data = asyncio.run(_get_project())
543
+ if not project_data:
544
+ console.print(f"[red]Error: Project '{name}' not found[/red]")
545
+ raise typer.Exit(1)
546
+
547
+ # Get local_sync_path from cloud_projects config
548
+ local_sync_path = None
549
+ if name in config.cloud_projects:
550
+ local_sync_path = config.cloud_projects[name].local_path
551
+
552
+ if not local_sync_path:
553
+ console.print(f"[red]Error: Project '{name}' has no local_sync_path configured[/red]")
554
+ console.print(f"\nConfigure sync with: bm project sync-setup {name} ~/path/to/local")
555
+ raise typer.Exit(1)
556
+
557
+ # Create SyncProject
558
+ sync_project = SyncProject(
559
+ name=project_data.name,
560
+ path=normalize_project_path(project_data.path),
561
+ local_sync_path=local_sync_path,
562
+ )
563
+
564
+ # Run bisync
565
+ console.print(f"[blue]Bisync {name} (local <-> cloud)...[/blue]")
566
+ success = project_bisync(
567
+ sync_project, bucket_name, dry_run=dry_run, resync=resync, verbose=verbose
568
+ )
569
+
570
+ if success:
571
+ console.print(f"[green]{name} bisync completed successfully[/green]")
572
+
573
+ # Update config
574
+ config.cloud_projects[name].last_sync = datetime.now()
575
+ config.cloud_projects[name].bisync_initialized = True
576
+ ConfigManager().save_config(config)
577
+
578
+ # Trigger database sync if not a dry run
579
+ if not dry_run:
580
+
581
+ async def _trigger_db_sync():
582
+ async with get_client() as client:
583
+ permalink = generate_permalink(name)
584
+ response = await call_post(
585
+ client, f"/{permalink}/project/sync?force_full=true", json={}
586
+ )
587
+ return response.json()
588
+
589
+ try:
590
+ result = asyncio.run(_trigger_db_sync())
591
+ console.print(f"[dim]Database sync initiated: {result.get('message')}[/dim]")
592
+ except Exception as e:
593
+ console.print(f"[yellow]Warning: Could not trigger database sync: {e}[/yellow]")
594
+ else:
595
+ console.print(f"[red]{name} bisync failed[/red]")
596
+ raise typer.Exit(1)
597
+
598
+ except RcloneError as e:
599
+ console.print(f"[red]Bisync error: {e}[/red]")
600
+ raise typer.Exit(1)
601
+ except Exception as e:
602
+ console.print(f"[red]Error: {e}[/red]")
603
+ raise typer.Exit(1)
604
+
605
+
606
+ @project_app.command("check")
607
+ def check_project_command(
608
+ name: str = typer.Option(..., "--name", help="Project name to check"),
609
+ one_way: bool = typer.Option(False, "--one-way", help="Check one direction only (faster)"),
610
+ ) -> None:
611
+ """Verify file integrity between local and cloud.
612
+
613
+ Example:
614
+ bm project check --name research
615
+ """
616
+ config = ConfigManager().config
617
+ if not config.cloud_mode_enabled:
618
+ console.print("[red]Error: check only available in cloud mode[/red]")
619
+ raise typer.Exit(1)
620
+
621
+ try:
622
+ # Get tenant info for bucket name
623
+ tenant_info = asyncio.run(get_mount_info())
624
+ bucket_name = tenant_info.bucket_name
625
+
626
+ # Get project info
627
+ async def _get_project():
628
+ async with get_client() as client:
629
+ response = await call_get(client, "/projects/projects")
630
+ projects_list = ProjectList.model_validate(response.json())
631
+ for proj in projects_list.projects:
632
+ if generate_permalink(proj.name) == generate_permalink(name):
633
+ return proj
634
+ return None
635
+
636
+ project_data = asyncio.run(_get_project())
637
+ if not project_data:
638
+ console.print(f"[red]Error: Project '{name}' not found[/red]")
639
+ raise typer.Exit(1)
640
+
641
+ # Get local_sync_path from cloud_projects config
642
+ local_sync_path = None
643
+ if name in config.cloud_projects:
644
+ local_sync_path = config.cloud_projects[name].local_path
645
+
646
+ if not local_sync_path:
647
+ console.print(f"[red]Error: Project '{name}' has no local_sync_path configured[/red]")
648
+ console.print(f"\nConfigure sync with: bm project sync-setup {name} ~/path/to/local")
649
+ raise typer.Exit(1)
650
+
651
+ # Create SyncProject
652
+ sync_project = SyncProject(
653
+ name=project_data.name,
654
+ path=normalize_project_path(project_data.path),
655
+ local_sync_path=local_sync_path,
656
+ )
657
+
658
+ # Run check
659
+ console.print(f"[blue]Checking {name} integrity...[/blue]")
660
+ match = project_check(sync_project, bucket_name, one_way=one_way)
661
+
662
+ if match:
663
+ console.print(f"[green]{name} files match[/green]")
664
+ else:
665
+ console.print(f"[yellow]!{name} has differences[/yellow]")
666
+
667
+ except RcloneError as e:
668
+ console.print(f"[red]Check error: {e}[/red]")
669
+ raise typer.Exit(1)
670
+ except Exception as e:
671
+ console.print(f"[red]Error: {e}[/red]")
672
+ raise typer.Exit(1)
673
+
674
+
675
+ @project_app.command("bisync-reset")
676
+ def bisync_reset(
677
+ name: str = typer.Argument(..., help="Project name to reset bisync state for"),
678
+ ) -> None:
679
+ """Clear bisync state for a project.
680
+
681
+ This removes the bisync metadata files, forcing a fresh --resync on next bisync.
682
+ Useful when bisync gets into an inconsistent state or when remote path changes.
683
+ """
684
+ from basic_memory.cli.commands.cloud.rclone_commands import get_project_bisync_state
685
+ import shutil
686
+
687
+ try:
688
+ state_path = get_project_bisync_state(name)
689
+
690
+ if not state_path.exists():
691
+ console.print(f"[yellow]No bisync state found for project '{name}'[/yellow]")
692
+ return
693
+
694
+ # Remove the entire state directory
695
+ shutil.rmtree(state_path)
696
+ console.print(f"[green]Cleared bisync state for project '{name}'[/green]")
697
+ console.print("\nNext steps:")
698
+ console.print(f" 1. Preview: bm project bisync --name {name} --resync --dry-run")
699
+ console.print(f" 2. Sync: bm project bisync --name {name} --resync")
700
+
701
+ except Exception as e:
702
+ console.print(f"[red]Error clearing bisync state: {str(e)}[/red]")
703
+ raise typer.Exit(1)
704
+
705
+
706
+ @project_app.command("ls")
707
+ def ls_project_command(
708
+ name: str = typer.Option(..., "--name", help="Project name to list files from"),
709
+ path: str = typer.Argument(None, help="Path within project (optional)"),
710
+ ) -> None:
711
+ """List files in remote project.
712
+
713
+ Examples:
714
+ bm project ls --name research
715
+ bm project ls --name research subfolder
716
+ """
717
+ config = ConfigManager().config
718
+ if not config.cloud_mode_enabled:
719
+ console.print("[red]Error: ls only available in cloud mode[/red]")
720
+ raise typer.Exit(1)
721
+
722
+ try:
723
+ # Get tenant info for bucket name
724
+ tenant_info = asyncio.run(get_mount_info())
725
+ bucket_name = tenant_info.bucket_name
726
+
727
+ # Get project info
728
+ async def _get_project():
729
+ async with get_client() as client:
730
+ response = await call_get(client, "/projects/projects")
731
+ projects_list = ProjectList.model_validate(response.json())
732
+ for proj in projects_list.projects:
733
+ if generate_permalink(proj.name) == generate_permalink(name):
734
+ return proj
735
+ return None
736
+
737
+ project_data = asyncio.run(_get_project())
738
+ if not project_data:
739
+ console.print(f"[red]Error: Project '{name}' not found[/red]")
740
+ raise typer.Exit(1)
741
+
742
+ # Create SyncProject (local_sync_path not needed for ls)
743
+ sync_project = SyncProject(
744
+ name=project_data.name,
745
+ path=normalize_project_path(project_data.path),
746
+ )
747
+
748
+ # List files
749
+ files = project_ls(sync_project, bucket_name, path=path)
750
+
751
+ if files:
752
+ console.print(f"\n[bold]Files in {name}" + (f"/{path}" if path else "") + ":[/bold]")
753
+ for file in files:
754
+ console.print(f" {file}")
755
+ console.print(f"\n[dim]Total: {len(files)} files[/dim]")
756
+ else:
757
+ console.print(
758
+ f"[yellow]No files found in {name}" + (f"/{path}" if path else "") + "[/yellow]"
759
+ )
760
+
761
+ except Exception as e:
762
+ console.print(f"[red]Error: {e}[/red]")
763
+ raise typer.Exit(1)
764
+
765
+
766
+ @project_app.command("info")
767
+ def display_project_info(
768
+ name: str = typer.Argument(..., help="Name of the project"),
769
+ json_output: bool = typer.Option(False, "--json", help="Output in JSON format"),
770
+ ):
771
+ """Display detailed information and statistics about the current project."""
772
+ try:
773
+ # Get project info
774
+ info = asyncio.run(get_project_info(name))
775
+
776
+ if json_output:
777
+ # Convert to JSON and print
778
+ print(json.dumps(info.model_dump(), indent=2, default=str))
779
+ else:
780
+ # Project configuration section
781
+ console.print(
782
+ Panel(
783
+ f"Basic Memory version: [bold green]{info.system.version}[/bold green]\n"
784
+ f"[bold]Project:[/bold] {info.project_name}\n"
785
+ f"[bold]Path:[/bold] {info.project_path}\n"
786
+ f"[bold]Default Project:[/bold] {info.default_project}\n",
787
+ title="Basic Memory Project Info",
788
+ expand=False,
789
+ )
790
+ )
791
+
792
+ # Statistics section
793
+ stats_table = Table(title="Statistics")
794
+ stats_table.add_column("Metric", style="cyan")
795
+ stats_table.add_column("Count", style="green")
796
+
797
+ stats_table.add_row("Entities", str(info.statistics.total_entities))
798
+ stats_table.add_row("Observations", str(info.statistics.total_observations))
799
+ stats_table.add_row("Relations", str(info.statistics.total_relations))
800
+ stats_table.add_row(
801
+ "Unresolved Relations", str(info.statistics.total_unresolved_relations)
802
+ )
803
+ stats_table.add_row("Isolated Entities", str(info.statistics.isolated_entities))
804
+
805
+ console.print(stats_table)
806
+
807
+ # Entity types
808
+ if info.statistics.entity_types:
809
+ entity_types_table = Table(title="Entity Types")
810
+ entity_types_table.add_column("Type", style="blue")
811
+ entity_types_table.add_column("Count", style="green")
812
+
813
+ for entity_type, count in info.statistics.entity_types.items():
814
+ entity_types_table.add_row(entity_type, str(count))
815
+
816
+ console.print(entity_types_table)
817
+
818
+ # Most connected entities
819
+ if info.statistics.most_connected_entities: # pragma: no cover
820
+ connected_table = Table(title="Most Connected Entities")
821
+ connected_table.add_column("Title", style="blue")
822
+ connected_table.add_column("Permalink", style="cyan")
823
+ connected_table.add_column("Relations", style="green")
824
+
825
+ for entity in info.statistics.most_connected_entities:
826
+ connected_table.add_row(
827
+ entity["title"], entity["permalink"], str(entity["relation_count"])
828
+ )
829
+
830
+ console.print(connected_table)
831
+
832
+ # Recent activity
833
+ if info.activity.recently_updated: # pragma: no cover
834
+ recent_table = Table(title="Recent Activity")
835
+ recent_table.add_column("Title", style="blue")
836
+ recent_table.add_column("Type", style="cyan")
837
+ recent_table.add_column("Last Updated", style="green")
838
+
839
+ for entity in info.activity.recently_updated[:5]: # Show top 5
840
+ updated_at = (
841
+ datetime.fromisoformat(entity["updated_at"])
842
+ if isinstance(entity["updated_at"], str)
843
+ else entity["updated_at"]
844
+ )
845
+ recent_table.add_row(
846
+ entity["title"],
847
+ entity["entity_type"],
848
+ updated_at.strftime("%Y-%m-%d %H:%M"),
849
+ )
850
+
851
+ console.print(recent_table)
852
+
853
+ # Available projects
854
+ projects_table = Table(title="Available Projects")
855
+ projects_table.add_column("Name", style="blue")
856
+ projects_table.add_column("Path", style="cyan")
857
+ projects_table.add_column("Default", style="green")
858
+
859
+ for name, proj_info in info.available_projects.items():
860
+ is_default = name == info.default_project
861
+ project_path = proj_info["path"]
862
+ projects_table.add_row(name, project_path, "[X]" if is_default else "")
863
+
864
+ console.print(projects_table)
865
+
866
+ # Timestamp
867
+ current_time = (
868
+ datetime.fromisoformat(str(info.system.timestamp))
869
+ if isinstance(info.system.timestamp, str)
870
+ else info.system.timestamp
871
+ )
872
+ console.print(f"\nTimestamp: [cyan]{current_time.strftime('%Y-%m-%d %H:%M:%S')}[/cyan]")
873
+
874
+ except Exception as e: # pragma: no cover
875
+ typer.echo(f"Error getting project info: {e}", err=True)
876
+ raise typer.Exit(1)