basic-memory 0.17.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. basic_memory/__init__.py +7 -0
  2. basic_memory/alembic/alembic.ini +119 -0
  3. basic_memory/alembic/env.py +185 -0
  4. basic_memory/alembic/migrations.py +24 -0
  5. basic_memory/alembic/script.py.mako +26 -0
  6. basic_memory/alembic/versions/314f1ea54dc4_add_postgres_full_text_search_support_.py +131 -0
  7. basic_memory/alembic/versions/3dae7c7b1564_initial_schema.py +93 -0
  8. basic_memory/alembic/versions/502b60eaa905_remove_required_from_entity_permalink.py +51 -0
  9. basic_memory/alembic/versions/5fe1ab1ccebe_add_projects_table.py +120 -0
  10. basic_memory/alembic/versions/647e7a75e2cd_project_constraint_fix.py +112 -0
  11. basic_memory/alembic/versions/9d9c1cb7d8f5_add_mtime_and_size_columns_to_entity_.py +49 -0
  12. basic_memory/alembic/versions/a1b2c3d4e5f6_fix_project_foreign_keys.py +49 -0
  13. basic_memory/alembic/versions/a2b3c4d5e6f7_add_search_index_entity_cascade.py +56 -0
  14. basic_memory/alembic/versions/b3c3938bacdb_relation_to_name_unique_index.py +44 -0
  15. basic_memory/alembic/versions/cc7172b46608_update_search_index_schema.py +113 -0
  16. basic_memory/alembic/versions/e7e1f4367280_add_scan_watermark_tracking_to_project.py +37 -0
  17. basic_memory/alembic/versions/f8a9b2c3d4e5_add_pg_trgm_for_fuzzy_link_resolution.py +239 -0
  18. basic_memory/api/__init__.py +5 -0
  19. basic_memory/api/app.py +131 -0
  20. basic_memory/api/routers/__init__.py +11 -0
  21. basic_memory/api/routers/directory_router.py +84 -0
  22. basic_memory/api/routers/importer_router.py +152 -0
  23. basic_memory/api/routers/knowledge_router.py +318 -0
  24. basic_memory/api/routers/management_router.py +80 -0
  25. basic_memory/api/routers/memory_router.py +90 -0
  26. basic_memory/api/routers/project_router.py +448 -0
  27. basic_memory/api/routers/prompt_router.py +260 -0
  28. basic_memory/api/routers/resource_router.py +249 -0
  29. basic_memory/api/routers/search_router.py +36 -0
  30. basic_memory/api/routers/utils.py +169 -0
  31. basic_memory/api/template_loader.py +292 -0
  32. basic_memory/api/v2/__init__.py +35 -0
  33. basic_memory/api/v2/routers/__init__.py +21 -0
  34. basic_memory/api/v2/routers/directory_router.py +93 -0
  35. basic_memory/api/v2/routers/importer_router.py +182 -0
  36. basic_memory/api/v2/routers/knowledge_router.py +413 -0
  37. basic_memory/api/v2/routers/memory_router.py +130 -0
  38. basic_memory/api/v2/routers/project_router.py +342 -0
  39. basic_memory/api/v2/routers/prompt_router.py +270 -0
  40. basic_memory/api/v2/routers/resource_router.py +286 -0
  41. basic_memory/api/v2/routers/search_router.py +73 -0
  42. basic_memory/cli/__init__.py +1 -0
  43. basic_memory/cli/app.py +84 -0
  44. basic_memory/cli/auth.py +277 -0
  45. basic_memory/cli/commands/__init__.py +18 -0
  46. basic_memory/cli/commands/cloud/__init__.py +6 -0
  47. basic_memory/cli/commands/cloud/api_client.py +112 -0
  48. basic_memory/cli/commands/cloud/bisync_commands.py +110 -0
  49. basic_memory/cli/commands/cloud/cloud_utils.py +101 -0
  50. basic_memory/cli/commands/cloud/core_commands.py +195 -0
  51. basic_memory/cli/commands/cloud/rclone_commands.py +371 -0
  52. basic_memory/cli/commands/cloud/rclone_config.py +110 -0
  53. basic_memory/cli/commands/cloud/rclone_installer.py +263 -0
  54. basic_memory/cli/commands/cloud/upload.py +233 -0
  55. basic_memory/cli/commands/cloud/upload_command.py +124 -0
  56. basic_memory/cli/commands/command_utils.py +77 -0
  57. basic_memory/cli/commands/db.py +44 -0
  58. basic_memory/cli/commands/format.py +198 -0
  59. basic_memory/cli/commands/import_chatgpt.py +84 -0
  60. basic_memory/cli/commands/import_claude_conversations.py +87 -0
  61. basic_memory/cli/commands/import_claude_projects.py +86 -0
  62. basic_memory/cli/commands/import_memory_json.py +87 -0
  63. basic_memory/cli/commands/mcp.py +76 -0
  64. basic_memory/cli/commands/project.py +889 -0
  65. basic_memory/cli/commands/status.py +174 -0
  66. basic_memory/cli/commands/telemetry.py +81 -0
  67. basic_memory/cli/commands/tool.py +341 -0
  68. basic_memory/cli/main.py +28 -0
  69. basic_memory/config.py +616 -0
  70. basic_memory/db.py +394 -0
  71. basic_memory/deps.py +705 -0
  72. basic_memory/file_utils.py +478 -0
  73. basic_memory/ignore_utils.py +297 -0
  74. basic_memory/importers/__init__.py +27 -0
  75. basic_memory/importers/base.py +79 -0
  76. basic_memory/importers/chatgpt_importer.py +232 -0
  77. basic_memory/importers/claude_conversations_importer.py +180 -0
  78. basic_memory/importers/claude_projects_importer.py +148 -0
  79. basic_memory/importers/memory_json_importer.py +108 -0
  80. basic_memory/importers/utils.py +61 -0
  81. basic_memory/markdown/__init__.py +21 -0
  82. basic_memory/markdown/entity_parser.py +279 -0
  83. basic_memory/markdown/markdown_processor.py +160 -0
  84. basic_memory/markdown/plugins.py +242 -0
  85. basic_memory/markdown/schemas.py +70 -0
  86. basic_memory/markdown/utils.py +117 -0
  87. basic_memory/mcp/__init__.py +1 -0
  88. basic_memory/mcp/async_client.py +139 -0
  89. basic_memory/mcp/project_context.py +141 -0
  90. basic_memory/mcp/prompts/__init__.py +19 -0
  91. basic_memory/mcp/prompts/ai_assistant_guide.py +70 -0
  92. basic_memory/mcp/prompts/continue_conversation.py +62 -0
  93. basic_memory/mcp/prompts/recent_activity.py +188 -0
  94. basic_memory/mcp/prompts/search.py +57 -0
  95. basic_memory/mcp/prompts/utils.py +162 -0
  96. basic_memory/mcp/resources/ai_assistant_guide.md +283 -0
  97. basic_memory/mcp/resources/project_info.py +71 -0
  98. basic_memory/mcp/server.py +81 -0
  99. basic_memory/mcp/tools/__init__.py +48 -0
  100. basic_memory/mcp/tools/build_context.py +120 -0
  101. basic_memory/mcp/tools/canvas.py +152 -0
  102. basic_memory/mcp/tools/chatgpt_tools.py +190 -0
  103. basic_memory/mcp/tools/delete_note.py +242 -0
  104. basic_memory/mcp/tools/edit_note.py +324 -0
  105. basic_memory/mcp/tools/list_directory.py +168 -0
  106. basic_memory/mcp/tools/move_note.py +551 -0
  107. basic_memory/mcp/tools/project_management.py +201 -0
  108. basic_memory/mcp/tools/read_content.py +281 -0
  109. basic_memory/mcp/tools/read_note.py +267 -0
  110. basic_memory/mcp/tools/recent_activity.py +534 -0
  111. basic_memory/mcp/tools/search.py +385 -0
  112. basic_memory/mcp/tools/utils.py +540 -0
  113. basic_memory/mcp/tools/view_note.py +78 -0
  114. basic_memory/mcp/tools/write_note.py +230 -0
  115. basic_memory/models/__init__.py +15 -0
  116. basic_memory/models/base.py +10 -0
  117. basic_memory/models/knowledge.py +226 -0
  118. basic_memory/models/project.py +87 -0
  119. basic_memory/models/search.py +85 -0
  120. basic_memory/repository/__init__.py +11 -0
  121. basic_memory/repository/entity_repository.py +503 -0
  122. basic_memory/repository/observation_repository.py +73 -0
  123. basic_memory/repository/postgres_search_repository.py +379 -0
  124. basic_memory/repository/project_info_repository.py +10 -0
  125. basic_memory/repository/project_repository.py +128 -0
  126. basic_memory/repository/relation_repository.py +146 -0
  127. basic_memory/repository/repository.py +385 -0
  128. basic_memory/repository/search_index_row.py +95 -0
  129. basic_memory/repository/search_repository.py +94 -0
  130. basic_memory/repository/search_repository_base.py +241 -0
  131. basic_memory/repository/sqlite_search_repository.py +439 -0
  132. basic_memory/schemas/__init__.py +86 -0
  133. basic_memory/schemas/base.py +297 -0
  134. basic_memory/schemas/cloud.py +50 -0
  135. basic_memory/schemas/delete.py +37 -0
  136. basic_memory/schemas/directory.py +30 -0
  137. basic_memory/schemas/importer.py +35 -0
  138. basic_memory/schemas/memory.py +285 -0
  139. basic_memory/schemas/project_info.py +212 -0
  140. basic_memory/schemas/prompt.py +90 -0
  141. basic_memory/schemas/request.py +112 -0
  142. basic_memory/schemas/response.py +229 -0
  143. basic_memory/schemas/search.py +117 -0
  144. basic_memory/schemas/sync_report.py +72 -0
  145. basic_memory/schemas/v2/__init__.py +27 -0
  146. basic_memory/schemas/v2/entity.py +129 -0
  147. basic_memory/schemas/v2/resource.py +46 -0
  148. basic_memory/services/__init__.py +8 -0
  149. basic_memory/services/context_service.py +601 -0
  150. basic_memory/services/directory_service.py +308 -0
  151. basic_memory/services/entity_service.py +864 -0
  152. basic_memory/services/exceptions.py +37 -0
  153. basic_memory/services/file_service.py +541 -0
  154. basic_memory/services/initialization.py +216 -0
  155. basic_memory/services/link_resolver.py +121 -0
  156. basic_memory/services/project_service.py +880 -0
  157. basic_memory/services/search_service.py +404 -0
  158. basic_memory/services/service.py +15 -0
  159. basic_memory/sync/__init__.py +6 -0
  160. basic_memory/sync/background_sync.py +26 -0
  161. basic_memory/sync/sync_service.py +1259 -0
  162. basic_memory/sync/watch_service.py +510 -0
  163. basic_memory/telemetry.py +249 -0
  164. basic_memory/templates/prompts/continue_conversation.hbs +110 -0
  165. basic_memory/templates/prompts/search.hbs +101 -0
  166. basic_memory/utils.py +468 -0
  167. basic_memory-0.17.1.dist-info/METADATA +617 -0
  168. basic_memory-0.17.1.dist-info/RECORD +171 -0
  169. basic_memory-0.17.1.dist-info/WHEEL +4 -0
  170. basic_memory-0.17.1.dist-info/entry_points.txt +3 -0
  171. basic_memory-0.17.1.dist-info/licenses/LICENSE +661 -0
@@ -0,0 +1,169 @@
1
+ from typing import Optional, List
2
+
3
+ from basic_memory.repository import EntityRepository
4
+ from basic_memory.repository.search_repository import SearchIndexRow
5
+ from basic_memory.schemas.memory import (
6
+ EntitySummary,
7
+ ObservationSummary,
8
+ RelationSummary,
9
+ MemoryMetadata,
10
+ GraphContext,
11
+ ContextResult,
12
+ )
13
+ from basic_memory.schemas.search import SearchItemType, SearchResult
14
+ from basic_memory.services import EntityService
15
+ from basic_memory.services.context_service import (
16
+ ContextResultRow,
17
+ ContextResult as ServiceContextResult,
18
+ )
19
+
20
+
21
+ async def to_graph_context(
22
+ context_result: ServiceContextResult,
23
+ entity_repository: EntityRepository,
24
+ page: Optional[int] = None,
25
+ page_size: Optional[int] = None,
26
+ ):
27
+ # First pass: collect all entity IDs needed for relations
28
+ entity_ids_needed: set[int] = set()
29
+ for context_item in context_result.results:
30
+ for item in (
31
+ [context_item.primary_result] + context_item.observations + context_item.related_results
32
+ ):
33
+ if item.type == SearchItemType.RELATION:
34
+ if item.from_id: # pyright: ignore
35
+ entity_ids_needed.add(item.from_id) # pyright: ignore
36
+ if item.to_id:
37
+ entity_ids_needed.add(item.to_id)
38
+
39
+ # Batch fetch all entities at once
40
+ entity_lookup: dict[int, str] = {}
41
+ if entity_ids_needed:
42
+ entities = await entity_repository.find_by_ids(list(entity_ids_needed))
43
+ entity_lookup = {e.id: e.title for e in entities}
44
+
45
+ # Helper function to convert items to summaries
46
+ def to_summary(item: SearchIndexRow | ContextResultRow):
47
+ match item.type:
48
+ case SearchItemType.ENTITY:
49
+ return EntitySummary(
50
+ entity_id=item.id,
51
+ title=item.title, # pyright: ignore
52
+ permalink=item.permalink,
53
+ content=item.content,
54
+ file_path=item.file_path,
55
+ created_at=item.created_at,
56
+ )
57
+ case SearchItemType.OBSERVATION:
58
+ return ObservationSummary(
59
+ observation_id=item.id,
60
+ entity_id=item.entity_id, # pyright: ignore
61
+ title=item.title, # pyright: ignore
62
+ file_path=item.file_path,
63
+ category=item.category, # pyright: ignore
64
+ content=item.content, # pyright: ignore
65
+ permalink=item.permalink, # pyright: ignore
66
+ created_at=item.created_at,
67
+ )
68
+ case SearchItemType.RELATION:
69
+ from_title = entity_lookup.get(item.from_id) if item.from_id else None # pyright: ignore
70
+ to_title = entity_lookup.get(item.to_id) if item.to_id else None
71
+ return RelationSummary(
72
+ relation_id=item.id,
73
+ entity_id=item.entity_id, # pyright: ignore
74
+ title=item.title, # pyright: ignore
75
+ file_path=item.file_path,
76
+ permalink=item.permalink, # pyright: ignore
77
+ relation_type=item.relation_type, # pyright: ignore
78
+ from_entity=from_title,
79
+ from_entity_id=item.from_id, # pyright: ignore
80
+ to_entity=to_title,
81
+ to_entity_id=item.to_id,
82
+ created_at=item.created_at,
83
+ )
84
+ case _: # pragma: no cover
85
+ raise ValueError(f"Unexpected type: {item.type}")
86
+
87
+ # Process the hierarchical results
88
+ hierarchical_results = []
89
+ for context_item in context_result.results:
90
+ # Process primary result
91
+ primary_result = to_summary(context_item.primary_result)
92
+
93
+ # Process observations (always ObservationSummary, validated by context_service)
94
+ observations = [to_summary(obs) for obs in context_item.observations]
95
+
96
+ # Process related results
97
+ related = [to_summary(rel) for rel in context_item.related_results]
98
+
99
+ # Add to hierarchical results
100
+ hierarchical_results.append(
101
+ ContextResult(
102
+ primary_result=primary_result,
103
+ observations=observations, # pyright: ignore[reportArgumentType]
104
+ related_results=related,
105
+ )
106
+ )
107
+
108
+ # Create schema metadata from service metadata
109
+ metadata = MemoryMetadata(
110
+ uri=context_result.metadata.uri,
111
+ types=context_result.metadata.types,
112
+ depth=context_result.metadata.depth,
113
+ timeframe=context_result.metadata.timeframe,
114
+ generated_at=context_result.metadata.generated_at,
115
+ primary_count=context_result.metadata.primary_count,
116
+ related_count=context_result.metadata.related_count,
117
+ total_results=context_result.metadata.primary_count + context_result.metadata.related_count,
118
+ total_relations=context_result.metadata.total_relations,
119
+ total_observations=context_result.metadata.total_observations,
120
+ )
121
+
122
+ # Return new GraphContext with just hierarchical results
123
+ return GraphContext(
124
+ results=hierarchical_results,
125
+ metadata=metadata,
126
+ page=page,
127
+ page_size=page_size,
128
+ )
129
+
130
+
131
+ async def to_search_results(entity_service: EntityService, results: List[SearchIndexRow]):
132
+ search_results = []
133
+ for r in results:
134
+ entities = await entity_service.get_entities_by_id([r.entity_id, r.from_id, r.to_id]) # pyright: ignore
135
+
136
+ # Determine which IDs to set based on type
137
+ entity_id = None
138
+ observation_id = None
139
+ relation_id = None
140
+
141
+ if r.type == SearchItemType.ENTITY:
142
+ entity_id = r.id
143
+ elif r.type == SearchItemType.OBSERVATION:
144
+ observation_id = r.id
145
+ entity_id = r.entity_id # Parent entity
146
+ elif r.type == SearchItemType.RELATION:
147
+ relation_id = r.id
148
+ entity_id = r.entity_id # Parent entity
149
+
150
+ search_results.append(
151
+ SearchResult(
152
+ title=r.title, # pyright: ignore
153
+ type=r.type, # pyright: ignore
154
+ permalink=r.permalink,
155
+ score=r.score, # pyright: ignore
156
+ entity=entities[0].permalink if entities else None,
157
+ content=r.content,
158
+ file_path=r.file_path,
159
+ metadata=r.metadata,
160
+ entity_id=entity_id,
161
+ observation_id=observation_id,
162
+ relation_id=relation_id,
163
+ category=r.category,
164
+ from_entity=entities[0].permalink if entities else None,
165
+ to_entity=entities[1].permalink if len(entities) > 1 else None,
166
+ relation_type=r.relation_type,
167
+ )
168
+ )
169
+ return search_results
@@ -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
+ integer project IDs instead of name-based identifiers.
5
+
6
+ Key improvements:
7
+ - Direct project lookup via integer primary keys
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
15
+
16
+ from basic_memory.deps import DirectoryServiceV2Dep, ProjectIdPathDep
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: DirectoryServiceV2Dep,
25
+ project_id: ProjectIdPathDep,
26
+ ):
27
+ """Get hierarchical directory structure from the knowledge base.
28
+
29
+ Args:
30
+ directory_service: Service for directory operations
31
+ project_id: Numeric project ID
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: DirectoryServiceV2Dep,
46
+ project_id: ProjectIdPathDep,
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: Numeric project ID
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: DirectoryServiceV2Dep,
67
+ project_id: ProjectIdPathDep,
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: Numeric project ID
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