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
@@ -2,9 +2,10 @@
2
2
 
3
3
  import tempfile
4
4
  from pathlib import Path
5
+ from typing import Annotated
5
6
 
6
- from fastapi import APIRouter, HTTPException, BackgroundTasks
7
- from fastapi.responses import FileResponse
7
+ from fastapi import APIRouter, HTTPException, BackgroundTasks, Body
8
+ from fastapi.responses import FileResponse, JSONResponse
8
9
  from loguru import logger
9
10
 
10
11
  from basic_memory.deps import (
@@ -13,10 +14,13 @@ from basic_memory.deps import (
13
14
  SearchServiceDep,
14
15
  EntityServiceDep,
15
16
  FileServiceDep,
17
+ EntityRepositoryDep,
16
18
  )
17
19
  from basic_memory.repository.search_repository import SearchIndexRow
18
20
  from basic_memory.schemas.memory import normalize_memory_url
19
21
  from basic_memory.schemas.search import SearchQuery, SearchItemType
22
+ from basic_memory.models.knowledge import Entity as EntityModel
23
+ from datetime import datetime
20
24
 
21
25
  router = APIRouter(prefix="/resource", tags=["resources"])
22
26
 
@@ -94,8 +98,7 @@ async def get_resource_content(
94
98
  content = await file_service.read_entity_content(result)
95
99
  memory_url = normalize_memory_url(result.permalink)
96
100
  modified_date = result.updated_at.isoformat()
97
- assert result.checksum
98
- checksum = result.checksum[:8]
101
+ checksum = result.checksum[:8] if result.checksum else ""
99
102
 
100
103
  # Prepare the delimited content
101
104
  response_content = f"--- {memory_url} {modified_date} {checksum}\n"
@@ -122,3 +125,115 @@ def cleanup_temp_file(file_path: str):
122
125
  logger.debug(f"Temporary file deleted: {file_path}")
123
126
  except Exception as e: # pragma: no cover
124
127
  logger.error(f"Error deleting temporary file {file_path}: {e}")
128
+
129
+
130
+ @router.put("/{file_path:path}")
131
+ async def write_resource(
132
+ config: ProjectConfigDep,
133
+ file_service: FileServiceDep,
134
+ entity_repository: EntityRepositoryDep,
135
+ search_service: SearchServiceDep,
136
+ file_path: str,
137
+ content: Annotated[str, Body()],
138
+ ) -> JSONResponse:
139
+ """Write content to a file in the project.
140
+
141
+ This endpoint allows writing content directly to a file in the project.
142
+ Also creates an entity record and indexes the file for search.
143
+
144
+ Args:
145
+ file_path: Path to write to, relative to project root
146
+ request: Contains the content to write
147
+
148
+ Returns:
149
+ JSON response with file information
150
+ """
151
+ try:
152
+ # Get content from request body
153
+
154
+ # Defensive type checking: ensure content is a string
155
+ # FastAPI should validate this, but if a dict somehow gets through
156
+ # (e.g., via JSON body parsing), we need to catch it here
157
+ if isinstance(content, dict):
158
+ logger.error(
159
+ f"Error writing resource {file_path}: "
160
+ f"content is a dict, expected string. Keys: {list(content.keys())}"
161
+ )
162
+ raise HTTPException(
163
+ status_code=400,
164
+ detail="content must be a string, not a dict. "
165
+ "Ensure request body is sent as raw string content, not JSON object.",
166
+ )
167
+
168
+ # Ensure it's UTF-8 string content
169
+ if isinstance(content, bytes): # pragma: no cover
170
+ content_str = content.decode("utf-8")
171
+ else:
172
+ content_str = str(content)
173
+
174
+ # Get full file path
175
+ full_path = Path(f"{config.home}/{file_path}")
176
+
177
+ # Ensure parent directory exists
178
+ full_path.parent.mkdir(parents=True, exist_ok=True)
179
+
180
+ # Write content to file
181
+ checksum = await file_service.write_file(full_path, content_str)
182
+
183
+ # Get file info
184
+ file_stats = file_service.file_stats(full_path)
185
+
186
+ # Determine file details
187
+ file_name = Path(file_path).name
188
+ content_type = file_service.content_type(full_path)
189
+
190
+ entity_type = "canvas" if file_path.endswith(".canvas") else "file"
191
+
192
+ # Check if entity already exists
193
+ existing_entity = await entity_repository.get_by_file_path(file_path)
194
+
195
+ if existing_entity:
196
+ # Update existing entity
197
+ entity = await entity_repository.update(
198
+ existing_entity.id,
199
+ {
200
+ "title": file_name,
201
+ "entity_type": entity_type,
202
+ "content_type": content_type,
203
+ "file_path": file_path,
204
+ "checksum": checksum,
205
+ "updated_at": datetime.fromtimestamp(file_stats.st_mtime).astimezone(),
206
+ },
207
+ )
208
+ status_code = 200
209
+ else:
210
+ # Create a new entity model
211
+ entity = EntityModel(
212
+ title=file_name,
213
+ entity_type=entity_type,
214
+ content_type=content_type,
215
+ file_path=file_path,
216
+ checksum=checksum,
217
+ created_at=datetime.fromtimestamp(file_stats.st_ctime).astimezone(),
218
+ updated_at=datetime.fromtimestamp(file_stats.st_mtime).astimezone(),
219
+ )
220
+ entity = await entity_repository.add(entity)
221
+ status_code = 201
222
+
223
+ # Index the file for search
224
+ await search_service.index_entity(entity) # pyright: ignore
225
+
226
+ # Return success response
227
+ return JSONResponse(
228
+ status_code=status_code,
229
+ content={
230
+ "file_path": file_path,
231
+ "checksum": checksum,
232
+ "size": file_stats.st_size,
233
+ "created_at": file_stats.st_ctime,
234
+ "modified_at": file_stats.st_mtime,
235
+ },
236
+ )
237
+ except Exception as e: # pragma: no cover
238
+ logger.error(f"Error writing resource {file_path}: {e}")
239
+ raise HTTPException(status_code=500, detail=f"Failed to write resource: {str(e)}")
@@ -1,11 +1,10 @@
1
1
  """Router for search operations."""
2
2
 
3
- from dataclasses import asdict
4
-
5
3
  from fastapi import APIRouter, BackgroundTasks
6
4
 
7
- from basic_memory.schemas.search import SearchQuery, SearchResult, SearchResponse
8
- from basic_memory.deps import SearchServiceDep
5
+ from basic_memory.api.routers.utils import to_search_results
6
+ from basic_memory.schemas.search import SearchQuery, SearchResponse
7
+ from basic_memory.deps import SearchServiceDep, EntityServiceDep
9
8
 
10
9
  router = APIRouter(prefix="/search", tags=["search"])
11
10
 
@@ -14,6 +13,7 @@ router = APIRouter(prefix="/search", tags=["search"])
14
13
  async def search(
15
14
  query: SearchQuery,
16
15
  search_service: SearchServiceDep,
16
+ entity_service: EntityServiceDep,
17
17
  page: int = 1,
18
18
  page_size: int = 10,
19
19
  ):
@@ -21,7 +21,7 @@ async def search(
21
21
  limit = page_size
22
22
  offset = (page - 1) * page_size
23
23
  results = await search_service.search(query, limit=limit, offset=offset)
24
- search_results = [SearchResult.model_validate(asdict(r)) for r in results]
24
+ search_results = await to_search_results(entity_service, results)
25
25
  return SearchResponse(
26
26
  results=search_results,
27
27
  current_page=page,
@@ -0,0 +1,130 @@
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
+ # Helper function to convert items to summaries
28
+ async def to_summary(item: SearchIndexRow | ContextResultRow):
29
+ match item.type:
30
+ case SearchItemType.ENTITY:
31
+ return EntitySummary(
32
+ title=item.title, # pyright: ignore
33
+ permalink=item.permalink,
34
+ content=item.content,
35
+ file_path=item.file_path,
36
+ created_at=item.created_at,
37
+ )
38
+ case SearchItemType.OBSERVATION:
39
+ return ObservationSummary(
40
+ title=item.title, # pyright: ignore
41
+ file_path=item.file_path,
42
+ category=item.category, # pyright: ignore
43
+ content=item.content, # pyright: ignore
44
+ permalink=item.permalink, # pyright: ignore
45
+ created_at=item.created_at,
46
+ )
47
+ case SearchItemType.RELATION:
48
+ from_entity = await entity_repository.find_by_id(item.from_id) # pyright: ignore
49
+ to_entity = await entity_repository.find_by_id(item.to_id) if item.to_id else None
50
+ return RelationSummary(
51
+ title=item.title, # pyright: ignore
52
+ file_path=item.file_path,
53
+ permalink=item.permalink, # pyright: ignore
54
+ relation_type=item.relation_type, # pyright: ignore
55
+ from_entity=from_entity.title if from_entity else None,
56
+ to_entity=to_entity.title if to_entity else None,
57
+ created_at=item.created_at,
58
+ )
59
+ case _: # pragma: no cover
60
+ raise ValueError(f"Unexpected type: {item.type}")
61
+
62
+ # Process the hierarchical results
63
+ hierarchical_results = []
64
+ for context_item in context_result.results:
65
+ # Process primary result
66
+ primary_result = await to_summary(context_item.primary_result)
67
+
68
+ # Process observations
69
+ observations = []
70
+ for obs in context_item.observations:
71
+ observations.append(await to_summary(obs))
72
+
73
+ # Process related results
74
+ related = []
75
+ for rel in context_item.related_results:
76
+ related.append(await to_summary(rel))
77
+
78
+ # Add to hierarchical results
79
+ hierarchical_results.append(
80
+ ContextResult(
81
+ primary_result=primary_result,
82
+ observations=observations,
83
+ related_results=related,
84
+ )
85
+ )
86
+
87
+ # Create schema metadata from service metadata
88
+ metadata = MemoryMetadata(
89
+ uri=context_result.metadata.uri,
90
+ types=context_result.metadata.types,
91
+ depth=context_result.metadata.depth,
92
+ timeframe=context_result.metadata.timeframe,
93
+ generated_at=context_result.metadata.generated_at,
94
+ primary_count=context_result.metadata.primary_count,
95
+ related_count=context_result.metadata.related_count,
96
+ total_results=context_result.metadata.primary_count + context_result.metadata.related_count,
97
+ total_relations=context_result.metadata.total_relations,
98
+ total_observations=context_result.metadata.total_observations,
99
+ )
100
+
101
+ # Return new GraphContext with just hierarchical results
102
+ return GraphContext(
103
+ results=hierarchical_results,
104
+ metadata=metadata,
105
+ page=page,
106
+ page_size=page_size,
107
+ )
108
+
109
+
110
+ async def to_search_results(entity_service: EntityService, results: List[SearchIndexRow]):
111
+ search_results = []
112
+ for r in results:
113
+ entities = await entity_service.get_entities_by_id([r.entity_id, r.from_id, r.to_id]) # pyright: ignore
114
+ search_results.append(
115
+ SearchResult(
116
+ title=r.title, # pyright: ignore
117
+ type=r.type, # pyright: ignore
118
+ permalink=r.permalink,
119
+ score=r.score, # pyright: ignore
120
+ entity=entities[0].permalink if entities else None,
121
+ content=r.content,
122
+ file_path=r.file_path,
123
+ metadata=r.metadata,
124
+ category=r.category,
125
+ from_entity=entities[0].permalink if entities else None,
126
+ to_entity=entities[1].permalink if len(entities) > 1 else None,
127
+ relation_type=r.relation_type,
128
+ )
129
+ )
130
+ 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()
basic_memory/cli/app.py CHANGED
@@ -1,20 +1,54 @@
1
- import asyncio
1
+ from typing import Optional
2
2
 
3
3
  import typer
4
4
 
5
- from basic_memory import db
6
- from basic_memory.config import config
7
- from basic_memory.utils import setup_logging
5
+ from basic_memory.config import ConfigManager
8
6
 
9
- setup_logging(log_file=".basic-memory/basic-memory-cli.log", console=False) # pragma: no cover
10
7
 
11
- asyncio.run(db.run_migrations(config))
8
+ def version_callback(value: bool) -> None:
9
+ """Show version and exit."""
10
+ if value: # pragma: no cover
11
+ import basic_memory
12
+
13
+ typer.echo(f"Basic Memory version: {basic_memory.__version__}")
14
+ raise typer.Exit()
15
+
12
16
 
13
17
  app = typer.Typer(name="basic-memory")
14
18
 
15
- import_app = typer.Typer()
16
- app.add_typer(import_app, name="import")
19
+
20
+ @app.callback()
21
+ def app_callback(
22
+ ctx: typer.Context,
23
+ version: Optional[bool] = typer.Option(
24
+ None,
25
+ "--version",
26
+ "-v",
27
+ help="Show version and exit.",
28
+ callback=version_callback,
29
+ is_eager=True,
30
+ ),
31
+ ) -> None:
32
+ """Basic Memory - Local-first personal knowledge management."""
33
+
34
+ # Run initialization for every command unless --version was specified
35
+ if not version and ctx.invoked_subcommand is not None:
36
+ from basic_memory.services.initialization import ensure_initialization
37
+
38
+ app_config = ConfigManager().config
39
+ ensure_initialization(app_config)
17
40
 
18
41
 
19
- claude_app = typer.Typer()
42
+ ## import
43
+ # Register sub-command groups
44
+ import_app = typer.Typer(help="Import data from various sources")
45
+ app.add_typer(import_app, name="import")
46
+
47
+ claude_app = typer.Typer(help="Import Conversations from Claude JSON export.")
20
48
  import_app.add_typer(claude_app, name="claude")
49
+
50
+
51
+ ## cloud
52
+
53
+ cloud_app = typer.Typer(help="Access Basic Memory Cloud")
54
+ app.add_typer(cloud_app, name="cloud")