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,292 @@
1
+ """Template loading and rendering utilities for the Basic Memory API.
2
+
3
+ This module handles the loading and rendering of Handlebars templates from the
4
+ templates directory, providing a consistent interface for all prompt-related
5
+ formatting needs.
6
+ """
7
+
8
+ import textwrap
9
+ from typing import Dict, Any, Optional, Callable
10
+ from pathlib import Path
11
+ import json
12
+ import datetime
13
+
14
+ import pybars
15
+ from loguru import logger
16
+
17
+ # Get the base path of the templates directory
18
+ TEMPLATES_DIR = Path(__file__).parent.parent / "templates"
19
+
20
+
21
+ # Custom helpers for Handlebars
22
+ def _date_helper(this, *args):
23
+ """Format a date using the given format string."""
24
+ if len(args) < 1: # pragma: no cover
25
+ return ""
26
+
27
+ timestamp = args[0]
28
+ format_str = args[1] if len(args) > 1 else "%Y-%m-%d %H:%M"
29
+
30
+ if hasattr(timestamp, "strftime"):
31
+ result = timestamp.strftime(format_str)
32
+ elif isinstance(timestamp, str):
33
+ try:
34
+ dt = datetime.datetime.fromisoformat(timestamp)
35
+ result = dt.strftime(format_str)
36
+ except ValueError:
37
+ result = timestamp
38
+ else:
39
+ result = str(timestamp) # pragma: no cover
40
+
41
+ return pybars.strlist([result])
42
+
43
+
44
+ def _default_helper(this, *args):
45
+ """Return a default value if the given value is None or empty."""
46
+ if len(args) < 2: # pragma: no cover
47
+ return ""
48
+
49
+ value = args[0]
50
+ default_value = args[1]
51
+
52
+ result = default_value if value is None or value == "" else value
53
+ # Use strlist for consistent handling of HTML escaping
54
+ return pybars.strlist([str(result)])
55
+
56
+
57
+ def _capitalize_helper(this, *args):
58
+ """Capitalize the first letter of a string."""
59
+ if len(args) < 1: # pragma: no cover
60
+ return ""
61
+
62
+ text = args[0]
63
+ if not text or not isinstance(text, str): # pragma: no cover
64
+ result = ""
65
+ else:
66
+ result = text.capitalize()
67
+
68
+ return pybars.strlist([result])
69
+
70
+
71
+ def _round_helper(this, *args):
72
+ """Round a number to the specified number of decimal places."""
73
+ if len(args) < 1:
74
+ return ""
75
+
76
+ value = args[0]
77
+ decimal_places = args[1] if len(args) > 1 else 2
78
+
79
+ try:
80
+ result = str(round(float(value), int(decimal_places)))
81
+ except (ValueError, TypeError):
82
+ result = str(value)
83
+
84
+ return pybars.strlist([result])
85
+
86
+
87
+ def _size_helper(this, *args):
88
+ """Return the size/length of a collection."""
89
+ if len(args) < 1:
90
+ return 0
91
+
92
+ value = args[0]
93
+ if value is None:
94
+ result = "0"
95
+ elif isinstance(value, (list, tuple, dict, str)):
96
+ result = str(len(value)) # pragma: no cover
97
+ else: # pragma: no cover
98
+ result = "0"
99
+
100
+ return pybars.strlist([result])
101
+
102
+
103
+ def _json_helper(this, *args):
104
+ """Convert a value to a JSON string."""
105
+ if len(args) < 1: # pragma: no cover
106
+ return "{}"
107
+
108
+ value = args[0]
109
+ # For pybars, we need to return a SafeString to prevent HTML escaping
110
+ result = json.dumps(value) # pragma: no cover
111
+ # Safe string implementation to prevent HTML escaping
112
+ return pybars.strlist([result])
113
+
114
+
115
+ def _math_helper(this, *args):
116
+ """Perform basic math operations."""
117
+ if len(args) < 3:
118
+ return pybars.strlist(["Math error: Insufficient arguments"])
119
+
120
+ lhs = args[0]
121
+ operator = args[1]
122
+ rhs = args[2]
123
+
124
+ try:
125
+ lhs = float(lhs)
126
+ rhs = float(rhs)
127
+ if operator == "+":
128
+ result = str(lhs + rhs)
129
+ elif operator == "-":
130
+ result = str(lhs - rhs)
131
+ elif operator == "*":
132
+ result = str(lhs * rhs)
133
+ elif operator == "/":
134
+ result = str(lhs / rhs)
135
+ else:
136
+ result = f"Unsupported operator: {operator}"
137
+ except (ValueError, TypeError) as e:
138
+ result = f"Math error: {e}"
139
+
140
+ return pybars.strlist([result])
141
+
142
+
143
+ def _lt_helper(this, *args):
144
+ """Check if left hand side is less than right hand side."""
145
+ if len(args) < 2:
146
+ return False
147
+
148
+ lhs = args[0]
149
+ rhs = args[1]
150
+
151
+ try:
152
+ return float(lhs) < float(rhs)
153
+ except (ValueError, TypeError):
154
+ # Fall back to string comparison for non-numeric values
155
+ return str(lhs) < str(rhs)
156
+
157
+
158
+ def _if_cond_helper(this, options, condition):
159
+ """Block helper for custom if conditionals."""
160
+ if condition:
161
+ return options["fn"](this)
162
+ elif "inverse" in options:
163
+ return options["inverse"](this)
164
+ return "" # pragma: no cover
165
+
166
+
167
+ def _dedent_helper(this, options):
168
+ """Dedent a block of text to remove common leading whitespace.
169
+
170
+ Usage:
171
+ {{#dedent}}
172
+ This text will have its
173
+ common leading whitespace removed
174
+ while preserving relative indentation.
175
+ {{/dedent}}
176
+ """
177
+ if "fn" not in options: # pragma: no cover
178
+ return ""
179
+
180
+ # Get the content from the block
181
+ content = options["fn"](this)
182
+
183
+ # Convert to string if it's a strlist
184
+ if (
185
+ isinstance(content, list)
186
+ or hasattr(content, "__iter__")
187
+ and not isinstance(content, (str, bytes))
188
+ ):
189
+ content_str = "".join(str(item) for item in content) # pragma: no cover
190
+ else:
191
+ content_str = str(content) # pragma: no cover
192
+
193
+ # Add trailing and leading newlines to ensure proper dedenting
194
+ # This is critical for textwrap.dedent to work correctly with mixed content
195
+ content_str = "\n" + content_str + "\n"
196
+
197
+ # Use textwrap to dedent the content and remove the extra newlines we added
198
+ dedented = textwrap.dedent(content_str)[1:-1]
199
+
200
+ # Return as a SafeString to prevent HTML escaping
201
+ return pybars.strlist([dedented]) # pragma: no cover
202
+
203
+
204
+ class TemplateLoader:
205
+ """Loader for Handlebars templates.
206
+
207
+ This class is responsible for loading templates from disk and rendering
208
+ them with the provided context data.
209
+ """
210
+
211
+ def __init__(self, template_dir: Optional[str] = None):
212
+ """Initialize the template loader.
213
+
214
+ Args:
215
+ template_dir: Optional custom template directory path
216
+ """
217
+ self.template_dir = Path(template_dir) if template_dir else TEMPLATES_DIR
218
+ self.template_cache: Dict[str, Callable] = {}
219
+ self.compiler = pybars.Compiler()
220
+
221
+ # Set up standard helpers
222
+ self.helpers = {
223
+ "date": _date_helper,
224
+ "default": _default_helper,
225
+ "capitalize": _capitalize_helper,
226
+ "round": _round_helper,
227
+ "size": _size_helper,
228
+ "json": _json_helper,
229
+ "math": _math_helper,
230
+ "lt": _lt_helper,
231
+ "if_cond": _if_cond_helper,
232
+ "dedent": _dedent_helper,
233
+ }
234
+
235
+ logger.debug(f"Initialized template loader with directory: {self.template_dir}")
236
+
237
+ def get_template(self, template_path: str) -> Callable:
238
+ """Get a template by path, using cache if available.
239
+
240
+ Args:
241
+ template_path: The path to the template, relative to the templates directory
242
+
243
+ Returns:
244
+ The compiled Handlebars template
245
+
246
+ Raises:
247
+ FileNotFoundError: If the template doesn't exist
248
+ """
249
+ if template_path in self.template_cache:
250
+ return self.template_cache[template_path]
251
+
252
+ # Convert from Liquid-style path to Handlebars extension
253
+ if template_path.endswith(".liquid"):
254
+ template_path = template_path.replace(".liquid", ".hbs")
255
+ elif not template_path.endswith(".hbs"):
256
+ template_path = f"{template_path}.hbs"
257
+
258
+ full_path = self.template_dir / template_path
259
+
260
+ if not full_path.exists():
261
+ raise FileNotFoundError(f"Template not found: {full_path}")
262
+
263
+ with open(full_path, "r", encoding="utf-8") as f:
264
+ template_str = f.read()
265
+
266
+ template = self.compiler.compile(template_str)
267
+ self.template_cache[template_path] = template
268
+
269
+ logger.debug(f"Loaded template: {template_path}")
270
+ return template
271
+
272
+ async def render(self, template_path: str, context: Dict[str, Any]) -> str:
273
+ """Render a template with the given context.
274
+
275
+ Args:
276
+ template_path: The path to the template, relative to the templates directory
277
+ context: The context data to pass to the template
278
+
279
+ Returns:
280
+ The rendered template as a string
281
+ """
282
+ template = self.get_template(template_path)
283
+ return template(context, helpers=self.helpers)
284
+
285
+ def clear_cache(self) -> None:
286
+ """Clear the template cache."""
287
+ self.template_cache.clear()
288
+ logger.debug("Template cache cleared")
289
+
290
+
291
+ # Global template loader instance
292
+ template_loader = TemplateLoader()
@@ -0,0 +1,35 @@
1
+ """API v2 module - ID-based entity references.
2
+
3
+ Version 2 of the Basic Memory API uses integer entity IDs as the primary
4
+ identifier for improved performance and stability.
5
+
6
+ Key changes from v1:
7
+ - Entity lookups use integer IDs instead of paths/permalinks
8
+ - Direct database queries instead of cascading resolution
9
+ - Stable references that don't change with file moves
10
+ - Better caching support
11
+
12
+ All v2 routers are registered with the /v2 prefix.
13
+ """
14
+
15
+ from basic_memory.api.v2.routers import (
16
+ knowledge_router,
17
+ memory_router,
18
+ project_router,
19
+ resource_router,
20
+ search_router,
21
+ directory_router,
22
+ prompt_router,
23
+ importer_router,
24
+ )
25
+
26
+ __all__ = [
27
+ "knowledge_router",
28
+ "memory_router",
29
+ "project_router",
30
+ "resource_router",
31
+ "search_router",
32
+ "directory_router",
33
+ "prompt_router",
34
+ "importer_router",
35
+ ]
@@ -0,0 +1,21 @@
1
+ """V2 API routers."""
2
+
3
+ from basic_memory.api.v2.routers.knowledge_router import router as knowledge_router
4
+ from basic_memory.api.v2.routers.project_router import router as project_router
5
+ from basic_memory.api.v2.routers.memory_router import router as memory_router
6
+ from basic_memory.api.v2.routers.search_router import router as search_router
7
+ from basic_memory.api.v2.routers.resource_router import router as resource_router
8
+ from basic_memory.api.v2.routers.directory_router import router as directory_router
9
+ from basic_memory.api.v2.routers.prompt_router import router as prompt_router
10
+ from basic_memory.api.v2.routers.importer_router import router as importer_router
11
+
12
+ __all__ = [
13
+ "knowledge_router",
14
+ "project_router",
15
+ "memory_router",
16
+ "search_router",
17
+ "resource_router",
18
+ "directory_router",
19
+ "prompt_router",
20
+ "importer_router",
21
+ ]
@@ -0,0 +1,93 @@
1
+ """V2 Directory Router - ID-based directory tree operations.
2
+
3
+ This router provides directory structure browsing for projects using
4
+ external_id UUIDs instead of name-based identifiers.
5
+
6
+ Key improvements:
7
+ - Direct project lookup via external_id UUIDs
8
+ - Consistent with other v2 endpoints
9
+ - Better performance through indexed queries
10
+ """
11
+
12
+ from typing import List, Optional
13
+
14
+ from fastapi import APIRouter, Query, Path
15
+
16
+ from basic_memory.deps import DirectoryServiceV2ExternalDep
17
+ from basic_memory.schemas.directory import DirectoryNode
18
+
19
+ router = APIRouter(prefix="/directory", tags=["directory-v2"])
20
+
21
+
22
+ @router.get("/tree", response_model=DirectoryNode, response_model_exclude_none=True)
23
+ async def get_directory_tree(
24
+ directory_service: DirectoryServiceV2ExternalDep,
25
+ project_id: str = Path(..., description="Project external UUID"),
26
+ ):
27
+ """Get hierarchical directory structure from the knowledge base.
28
+
29
+ Args:
30
+ directory_service: Service for directory operations
31
+ project_id: Project external UUID
32
+
33
+ Returns:
34
+ DirectoryNode representing the root of the hierarchical tree structure
35
+ """
36
+ # Get a hierarchical directory tree for the specific project
37
+ tree = await directory_service.get_directory_tree()
38
+
39
+ # Return the hierarchical tree
40
+ return tree
41
+
42
+
43
+ @router.get("/structure", response_model=DirectoryNode, response_model_exclude_none=True)
44
+ async def get_directory_structure(
45
+ directory_service: DirectoryServiceV2ExternalDep,
46
+ project_id: str = Path(..., description="Project external UUID"),
47
+ ):
48
+ """Get folder structure for navigation (no files).
49
+
50
+ Optimized endpoint for folder tree navigation. Returns only directory nodes
51
+ without file metadata. For full tree with files, use /directory/tree.
52
+
53
+ Args:
54
+ directory_service: Service for directory operations
55
+ project_id: Project external UUID
56
+
57
+ Returns:
58
+ DirectoryNode tree containing only folders (type="directory")
59
+ """
60
+ structure = await directory_service.get_directory_structure()
61
+ return structure
62
+
63
+
64
+ @router.get("/list", response_model=List[DirectoryNode], response_model_exclude_none=True)
65
+ async def list_directory(
66
+ directory_service: DirectoryServiceV2ExternalDep,
67
+ project_id: str = Path(..., description="Project external UUID"),
68
+ dir_name: str = Query("/", description="Directory path to list"),
69
+ depth: int = Query(1, ge=1, le=10, description="Recursion depth (1-10)"),
70
+ file_name_glob: Optional[str] = Query(
71
+ None, description="Glob pattern for filtering file names"
72
+ ),
73
+ ):
74
+ """List directory contents with filtering and depth control.
75
+
76
+ Args:
77
+ directory_service: Service for directory operations
78
+ project_id: Project external UUID
79
+ dir_name: Directory path to list (default: root "/")
80
+ depth: Recursion depth (1-10, default: 1 for immediate children only)
81
+ file_name_glob: Optional glob pattern for filtering file names (e.g., "*.md", "*meeting*")
82
+
83
+ Returns:
84
+ List of DirectoryNode objects matching the criteria
85
+ """
86
+ # Get directory listing with filtering
87
+ nodes = await directory_service.list_directory(
88
+ dir_name=dir_name,
89
+ depth=depth,
90
+ file_name_glob=file_name_glob,
91
+ )
92
+
93
+ return nodes
@@ -0,0 +1,181 @@
1
+ """V2 Import Router - ID-based data import operations.
2
+
3
+ This router uses v2 dependencies for consistent project handling with external_id UUIDs.
4
+ Import endpoints use project_id in the path for consistency with other v2 endpoints.
5
+ """
6
+
7
+ import json
8
+ import logging
9
+
10
+ from fastapi import APIRouter, Form, HTTPException, UploadFile, status, Path
11
+
12
+ from basic_memory.deps import (
13
+ ChatGPTImporterV2ExternalDep,
14
+ ClaudeConversationsImporterV2ExternalDep,
15
+ ClaudeProjectsImporterV2ExternalDep,
16
+ MemoryJsonImporterV2ExternalDep,
17
+ )
18
+ from basic_memory.importers import Importer
19
+ from basic_memory.schemas.importer import (
20
+ ChatImportResult,
21
+ EntityImportResult,
22
+ ProjectImportResult,
23
+ )
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+ router = APIRouter(prefix="/import", tags=["import-v2"])
28
+
29
+
30
+ @router.post("/chatgpt", response_model=ChatImportResult)
31
+ async def import_chatgpt(
32
+ importer: ChatGPTImporterV2ExternalDep,
33
+ file: UploadFile,
34
+ project_id: str = Path(..., description="Project external UUID"),
35
+ folder: str = Form("conversations"),
36
+ ) -> ChatImportResult:
37
+ """Import conversations from ChatGPT JSON export.
38
+
39
+ Args:
40
+ project_id: Project external UUID from URL path
41
+ file: The ChatGPT conversations.json file.
42
+ folder: The folder to place the files in.
43
+ importer: ChatGPT importer instance.
44
+
45
+ Returns:
46
+ ChatImportResult with import statistics.
47
+
48
+ Raises:
49
+ HTTPException: If import fails.
50
+ """
51
+ logger.info(f"V2 Importing ChatGPT conversations for project {project_id}")
52
+ return await import_file(importer, file, folder)
53
+
54
+
55
+ @router.post("/claude/conversations", response_model=ChatImportResult)
56
+ async def import_claude_conversations(
57
+ importer: ClaudeConversationsImporterV2ExternalDep,
58
+ file: UploadFile,
59
+ project_id: str = Path(..., description="Project external UUID"),
60
+ folder: str = Form("conversations"),
61
+ ) -> ChatImportResult:
62
+ """Import conversations from Claude conversations.json export.
63
+
64
+ Args:
65
+ project_id: Project external UUID from URL path
66
+ file: The Claude conversations.json file.
67
+ folder: The folder to place the files in.
68
+ importer: Claude conversations importer instance.
69
+
70
+ Returns:
71
+ ChatImportResult with import statistics.
72
+
73
+ Raises:
74
+ HTTPException: If import fails.
75
+ """
76
+ logger.info(f"V2 Importing Claude conversations for project {project_id}")
77
+ return await import_file(importer, file, folder)
78
+
79
+
80
+ @router.post("/claude/projects", response_model=ProjectImportResult)
81
+ async def import_claude_projects(
82
+ importer: ClaudeProjectsImporterV2ExternalDep,
83
+ file: UploadFile,
84
+ project_id: str = Path(..., description="Project external UUID"),
85
+ folder: str = Form("projects"),
86
+ ) -> ProjectImportResult:
87
+ """Import projects from Claude projects.json export.
88
+
89
+ Args:
90
+ project_id: Project external UUID from URL path
91
+ file: The Claude projects.json file.
92
+ folder: The base folder to place the files in.
93
+ importer: Claude projects importer instance.
94
+
95
+ Returns:
96
+ ProjectImportResult with import statistics.
97
+
98
+ Raises:
99
+ HTTPException: If import fails.
100
+ """
101
+ logger.info(f"V2 Importing Claude projects for project {project_id}")
102
+ return await import_file(importer, file, folder)
103
+
104
+
105
+ @router.post("/memory-json", response_model=EntityImportResult)
106
+ async def import_memory_json(
107
+ importer: MemoryJsonImporterV2ExternalDep,
108
+ file: UploadFile,
109
+ project_id: str = Path(..., description="Project external UUID"),
110
+ folder: str = Form("conversations"),
111
+ ) -> EntityImportResult:
112
+ """Import entities and relations from a memory.json file.
113
+
114
+ Args:
115
+ project_id: Project external UUID from URL path
116
+ file: The memory.json file.
117
+ folder: Optional destination folder within the project.
118
+ importer: Memory JSON importer instance.
119
+
120
+ Returns:
121
+ EntityImportResult with import statistics.
122
+
123
+ Raises:
124
+ HTTPException: If import fails.
125
+ """
126
+ logger.info(f"V2 Importing memory.json for project {project_id}")
127
+ try:
128
+ file_data = []
129
+ file_bytes = await file.read()
130
+ file_str = file_bytes.decode("utf-8")
131
+ for line in file_str.splitlines():
132
+ json_data = json.loads(line)
133
+ file_data.append(json_data)
134
+
135
+ result = await importer.import_data(file_data, folder)
136
+ if not result.success: # pragma: no cover
137
+ raise HTTPException(
138
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
139
+ detail=result.error_message or "Import failed",
140
+ )
141
+ except Exception as e:
142
+ logger.exception("V2 Import failed")
143
+ raise HTTPException(
144
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
145
+ detail=f"Import failed: {str(e)}",
146
+ )
147
+ return result
148
+
149
+
150
+ async def import_file(importer: Importer, file: UploadFile, destination_folder: str):
151
+ """Helper function to import a file using an importer instance.
152
+
153
+ Args:
154
+ importer: The importer instance to use
155
+ file: The file to import
156
+ destination_folder: Destination folder for imported content
157
+
158
+ Returns:
159
+ Import result from the importer
160
+
161
+ Raises:
162
+ HTTPException: If import fails
163
+ """
164
+ try:
165
+ # Process file
166
+ json_data = json.load(file.file)
167
+ result = await importer.import_data(json_data, destination_folder)
168
+ if not result.success: # pragma: no cover
169
+ raise HTTPException(
170
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
171
+ detail=result.error_message or "Import failed",
172
+ )
173
+
174
+ return result
175
+
176
+ except Exception as e:
177
+ logger.exception("V2 Import failed")
178
+ raise HTTPException(
179
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
180
+ detail=f"Import failed: {str(e)}",
181
+ )