basic-memory 0.8.0__py3-none-any.whl → 0.9.0__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.
- basic_memory/__init__.py +1 -1
- basic_memory/alembic/migrations.py +4 -9
- basic_memory/alembic/versions/cc7172b46608_update_search_index_schema.py +106 -0
- basic_memory/api/app.py +9 -6
- basic_memory/api/routers/__init__.py +2 -1
- basic_memory/api/routers/knowledge_router.py +30 -4
- basic_memory/api/routers/memory_router.py +3 -2
- basic_memory/api/routers/project_info_router.py +275 -0
- basic_memory/api/routers/search_router.py +22 -4
- basic_memory/cli/app.py +54 -3
- basic_memory/cli/commands/__init__.py +15 -2
- basic_memory/cli/commands/db.py +9 -13
- basic_memory/cli/commands/import_chatgpt.py +26 -30
- basic_memory/cli/commands/import_claude_conversations.py +27 -29
- basic_memory/cli/commands/import_claude_projects.py +29 -31
- basic_memory/cli/commands/import_memory_json.py +26 -28
- basic_memory/cli/commands/mcp.py +7 -1
- basic_memory/cli/commands/project.py +119 -0
- basic_memory/cli/commands/project_info.py +167 -0
- basic_memory/cli/commands/status.py +7 -9
- basic_memory/cli/commands/sync.py +54 -9
- basic_memory/cli/commands/{tools.py → tool.py} +92 -19
- basic_memory/cli/main.py +40 -1
- basic_memory/config.py +155 -7
- basic_memory/db.py +19 -4
- basic_memory/deps.py +10 -3
- basic_memory/file_utils.py +32 -16
- basic_memory/markdown/utils.py +5 -0
- basic_memory/mcp/main.py +1 -2
- basic_memory/mcp/prompts/__init__.py +6 -2
- basic_memory/mcp/prompts/ai_assistant_guide.py +6 -8
- basic_memory/mcp/prompts/continue_conversation.py +65 -126
- basic_memory/mcp/prompts/recent_activity.py +55 -13
- basic_memory/mcp/prompts/search.py +72 -17
- basic_memory/mcp/prompts/utils.py +139 -82
- basic_memory/mcp/server.py +1 -1
- basic_memory/mcp/tools/__init__.py +11 -22
- basic_memory/mcp/tools/build_context.py +85 -0
- basic_memory/mcp/tools/canvas.py +17 -19
- basic_memory/mcp/tools/delete_note.py +28 -0
- basic_memory/mcp/tools/project_info.py +51 -0
- basic_memory/mcp/tools/{resource.py → read_content.py} +42 -5
- basic_memory/mcp/tools/read_note.py +190 -0
- basic_memory/mcp/tools/recent_activity.py +100 -0
- basic_memory/mcp/tools/search.py +56 -17
- basic_memory/mcp/tools/utils.py +245 -17
- basic_memory/mcp/tools/write_note.py +124 -0
- basic_memory/models/search.py +2 -1
- basic_memory/repository/entity_repository.py +3 -2
- basic_memory/repository/project_info_repository.py +9 -0
- basic_memory/repository/repository.py +23 -6
- basic_memory/repository/search_repository.py +33 -10
- basic_memory/schemas/__init__.py +12 -0
- basic_memory/schemas/memory.py +3 -2
- basic_memory/schemas/project_info.py +96 -0
- basic_memory/schemas/search.py +27 -32
- basic_memory/services/context_service.py +3 -3
- basic_memory/services/entity_service.py +8 -2
- basic_memory/services/file_service.py +105 -53
- basic_memory/services/link_resolver.py +5 -45
- basic_memory/services/search_service.py +45 -16
- basic_memory/sync/sync_service.py +274 -39
- basic_memory/sync/watch_service.py +160 -30
- basic_memory/utils.py +40 -40
- basic_memory-0.9.0.dist-info/METADATA +736 -0
- basic_memory-0.9.0.dist-info/RECORD +99 -0
- basic_memory/mcp/prompts/json_canvas_spec.py +0 -25
- basic_memory/mcp/tools/knowledge.py +0 -68
- basic_memory/mcp/tools/memory.py +0 -177
- basic_memory/mcp/tools/notes.py +0 -201
- basic_memory-0.8.0.dist-info/METADATA +0 -379
- basic_memory-0.8.0.dist-info/RECORD +0 -91
- {basic_memory-0.8.0.dist-info → basic_memory-0.9.0.dist-info}/WHEEL +0 -0
- {basic_memory-0.8.0.dist-info → basic_memory-0.9.0.dist-info}/entry_points.txt +0 -0
- {basic_memory-0.8.0.dist-info → basic_memory-0.9.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -3,7 +3,6 @@
|
|
|
3
3
|
import asyncio
|
|
4
4
|
from typing import Set, Dict
|
|
5
5
|
|
|
6
|
-
import logfire
|
|
7
6
|
import typer
|
|
8
7
|
from loguru import logger
|
|
9
8
|
from rich.console import Console
|
|
@@ -134,11 +133,10 @@ def status(
|
|
|
134
133
|
verbose: bool = typer.Option(False, "--verbose", "-v", help="Show detailed file information"),
|
|
135
134
|
):
|
|
136
135
|
"""Show sync status between files and database."""
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
raise typer.Exit(code=1) # pragma: no cover
|
|
136
|
+
try:
|
|
137
|
+
sync_service = asyncio.run(get_sync_service())
|
|
138
|
+
asyncio.run(run_status(sync_service, verbose)) # pragma: no cover
|
|
139
|
+
except Exception as e:
|
|
140
|
+
logger.exception(f"Error checking status: {e}")
|
|
141
|
+
typer.echo(f"Error checking status: {e}", err=True)
|
|
142
|
+
raise typer.Exit(code=1) # pragma: no cover
|
|
@@ -93,8 +93,10 @@ def group_issues_by_directory(issues: List[ValidationIssue]) -> Dict[str, List[V
|
|
|
93
93
|
def display_sync_summary(knowledge: SyncReport):
|
|
94
94
|
"""Display a one-line summary of sync changes."""
|
|
95
95
|
total_changes = knowledge.total
|
|
96
|
+
project_name = config.project
|
|
97
|
+
|
|
96
98
|
if total_changes == 0:
|
|
97
|
-
console.print("[green]Everything up to date[/green]")
|
|
99
|
+
console.print(f"[green]Project '{project_name}': Everything up to date[/green]")
|
|
98
100
|
return
|
|
99
101
|
|
|
100
102
|
# Format as: "Synced X files (A new, B modified, C moved, D deleted)"
|
|
@@ -113,16 +115,18 @@ def display_sync_summary(knowledge: SyncReport):
|
|
|
113
115
|
if del_count:
|
|
114
116
|
changes.append(f"[red]{del_count} deleted[/red]")
|
|
115
117
|
|
|
116
|
-
console.print(f"Synced {total_changes} files ({', '.join(changes)})")
|
|
118
|
+
console.print(f"Project '{project_name}': Synced {total_changes} files ({', '.join(changes)})")
|
|
117
119
|
|
|
118
120
|
|
|
119
121
|
def display_detailed_sync_results(knowledge: SyncReport):
|
|
120
122
|
"""Display detailed sync results with trees."""
|
|
123
|
+
project_name = config.project
|
|
124
|
+
|
|
121
125
|
if knowledge.total == 0:
|
|
122
|
-
console.print("\n[green]Everything up to date[/green]")
|
|
126
|
+
console.print(f"\n[green]Project '{project_name}': Everything up to date[/green]")
|
|
123
127
|
return
|
|
124
128
|
|
|
125
|
-
console.print("\n[bold]Sync Results[/bold]")
|
|
129
|
+
console.print(f"\n[bold]Sync Results for Project '{project_name}'[/bold]")
|
|
126
130
|
|
|
127
131
|
if knowledge.total > 0:
|
|
128
132
|
knowledge_tree = Tree("[bold]Knowledge Files[/bold]")
|
|
@@ -150,23 +154,52 @@ def display_detailed_sync_results(knowledge: SyncReport):
|
|
|
150
154
|
|
|
151
155
|
async def run_sync(verbose: bool = False, watch: bool = False, console_status: bool = False):
|
|
152
156
|
"""Run sync operation."""
|
|
157
|
+
import time
|
|
158
|
+
|
|
159
|
+
start_time = time.time()
|
|
160
|
+
|
|
161
|
+
logger.info(
|
|
162
|
+
"Sync command started",
|
|
163
|
+
project=config.project,
|
|
164
|
+
watch_mode=watch,
|
|
165
|
+
verbose=verbose,
|
|
166
|
+
directory=str(config.home),
|
|
167
|
+
)
|
|
153
168
|
|
|
154
169
|
sync_service = await get_sync_service()
|
|
155
170
|
|
|
156
171
|
# Start watching if requested
|
|
157
172
|
if watch:
|
|
173
|
+
logger.info("Starting watch service after initial sync")
|
|
158
174
|
watch_service = WatchService(
|
|
159
175
|
sync_service=sync_service,
|
|
160
176
|
file_service=sync_service.entity_service.file_service,
|
|
161
177
|
config=config,
|
|
162
178
|
)
|
|
163
|
-
|
|
164
|
-
|
|
179
|
+
|
|
180
|
+
# full sync - no progress bars in watch mode
|
|
181
|
+
await sync_service.sync(config.home, show_progress=False)
|
|
182
|
+
|
|
165
183
|
# watch changes
|
|
166
184
|
await watch_service.run() # pragma: no cover
|
|
167
185
|
else:
|
|
168
|
-
# one time sync
|
|
169
|
-
|
|
186
|
+
# one time sync - use progress bars for better UX
|
|
187
|
+
logger.info("Running one-time sync")
|
|
188
|
+
knowledge_changes = await sync_service.sync(config.home, show_progress=True)
|
|
189
|
+
|
|
190
|
+
# Log results
|
|
191
|
+
duration_ms = int((time.time() - start_time) * 1000)
|
|
192
|
+
logger.info(
|
|
193
|
+
"Sync command completed",
|
|
194
|
+
project=config.project,
|
|
195
|
+
total_changes=knowledge_changes.total,
|
|
196
|
+
new_files=len(knowledge_changes.new),
|
|
197
|
+
modified_files=len(knowledge_changes.modified),
|
|
198
|
+
deleted_files=len(knowledge_changes.deleted),
|
|
199
|
+
moved_files=len(knowledge_changes.moves),
|
|
200
|
+
duration_ms=duration_ms,
|
|
201
|
+
)
|
|
202
|
+
|
|
170
203
|
# Display results
|
|
171
204
|
if verbose:
|
|
172
205
|
display_detailed_sync_results(knowledge_changes)
|
|
@@ -191,12 +224,24 @@ def sync(
|
|
|
191
224
|
) -> None:
|
|
192
225
|
"""Sync knowledge files with the database."""
|
|
193
226
|
try:
|
|
227
|
+
# Show which project we're syncing
|
|
228
|
+
if not watch: # Don't show in watch mode as it would break the UI
|
|
229
|
+
typer.echo(f"Syncing project: {config.project}")
|
|
230
|
+
typer.echo(f"Project path: {config.home}")
|
|
231
|
+
|
|
194
232
|
# Run sync
|
|
195
233
|
asyncio.run(run_sync(verbose=verbose, watch=watch))
|
|
196
234
|
|
|
197
235
|
except Exception as e: # pragma: no cover
|
|
198
236
|
if not isinstance(e, typer.Exit):
|
|
199
|
-
logger.exception(
|
|
237
|
+
logger.exception(
|
|
238
|
+
"Sync command failed",
|
|
239
|
+
project=config.project,
|
|
240
|
+
error=str(e),
|
|
241
|
+
error_type=type(e).__name__,
|
|
242
|
+
watch_mode=watch,
|
|
243
|
+
directory=str(config.home),
|
|
244
|
+
)
|
|
200
245
|
typer.echo(f"Error during sync: {e}", err=True)
|
|
201
246
|
raise typer.Exit(1)
|
|
202
247
|
raise
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"""CLI tool commands for Basic Memory."""
|
|
2
2
|
|
|
3
3
|
import asyncio
|
|
4
|
+
import sys
|
|
4
5
|
from typing import Optional, List, Annotated
|
|
5
6
|
|
|
6
7
|
import typer
|
|
@@ -9,7 +10,6 @@ from rich import print as rprint
|
|
|
9
10
|
|
|
10
11
|
from basic_memory.cli.app import app
|
|
11
12
|
from basic_memory.mcp.tools import build_context as mcp_build_context
|
|
12
|
-
from basic_memory.mcp.tools import get_entity as mcp_get_entity
|
|
13
13
|
from basic_memory.mcp.tools import read_note as mcp_read_note
|
|
14
14
|
from basic_memory.mcp.tools import recent_activity as mcp_recent_activity
|
|
15
15
|
from basic_memory.mcp.tools import search as mcp_search
|
|
@@ -20,24 +20,78 @@ from basic_memory.mcp.prompts.continue_conversation import (
|
|
|
20
20
|
continue_conversation as mcp_continue_conversation,
|
|
21
21
|
)
|
|
22
22
|
|
|
23
|
+
from basic_memory.mcp.prompts.recent_activity import (
|
|
24
|
+
recent_activity_prompt as recent_activity_prompt,
|
|
25
|
+
)
|
|
26
|
+
|
|
23
27
|
from basic_memory.schemas.base import TimeFrame
|
|
24
28
|
from basic_memory.schemas.memory import MemoryUrl
|
|
25
29
|
from basic_memory.schemas.search import SearchQuery, SearchItemType
|
|
26
30
|
|
|
27
31
|
tool_app = typer.Typer()
|
|
28
|
-
app.add_typer(tool_app, name="
|
|
32
|
+
app.add_typer(tool_app, name="tool", help="Direct access to MCP tools via CLI")
|
|
29
33
|
|
|
30
34
|
|
|
31
35
|
@tool_app.command()
|
|
32
36
|
def write_note(
|
|
33
37
|
title: Annotated[str, typer.Option(help="The title of the note")],
|
|
34
|
-
content: Annotated[str, typer.Option(help="The content of the note")],
|
|
35
38
|
folder: Annotated[str, typer.Option(help="The folder to create the note in")],
|
|
39
|
+
content: Annotated[
|
|
40
|
+
Optional[str],
|
|
41
|
+
typer.Option(
|
|
42
|
+
help="The content of the note. If not provided, content will be read from stdin. This allows piping content from other commands, e.g.: cat file.md | basic-memory tools write-note"
|
|
43
|
+
),
|
|
44
|
+
] = None,
|
|
36
45
|
tags: Annotated[
|
|
37
46
|
Optional[List[str]], typer.Option(help="A list of tags to apply to the note")
|
|
38
47
|
] = None,
|
|
39
48
|
):
|
|
49
|
+
"""Create or update a markdown note. Content can be provided as an argument or read from stdin.
|
|
50
|
+
|
|
51
|
+
Content can be provided in two ways:
|
|
52
|
+
1. Using the --content parameter
|
|
53
|
+
2. Piping content through stdin (if --content is not provided)
|
|
54
|
+
|
|
55
|
+
Examples:
|
|
56
|
+
|
|
57
|
+
# Using content parameter
|
|
58
|
+
basic-memory tools write-note --title "My Note" --folder "notes" --content "Note content"
|
|
59
|
+
|
|
60
|
+
# Using stdin pipe
|
|
61
|
+
echo "# My Note Content" | basic-memory tools write-note --title "My Note" --folder "notes"
|
|
62
|
+
|
|
63
|
+
# Using heredoc
|
|
64
|
+
cat << EOF | basic-memory tools write-note --title "My Note" --folder "notes"
|
|
65
|
+
# My Document
|
|
66
|
+
|
|
67
|
+
This is my document content.
|
|
68
|
+
|
|
69
|
+
- Point 1
|
|
70
|
+
- Point 2
|
|
71
|
+
EOF
|
|
72
|
+
|
|
73
|
+
# Reading from a file
|
|
74
|
+
cat document.md | basic-memory tools write-note --title "Document" --folder "docs"
|
|
75
|
+
"""
|
|
40
76
|
try:
|
|
77
|
+
# If content is not provided, read from stdin
|
|
78
|
+
if content is None:
|
|
79
|
+
# Check if we're getting data from a pipe or redirect
|
|
80
|
+
if not sys.stdin.isatty():
|
|
81
|
+
content = sys.stdin.read()
|
|
82
|
+
else: # pragma: no cover
|
|
83
|
+
# If stdin is a terminal (no pipe/redirect), inform the user
|
|
84
|
+
typer.echo(
|
|
85
|
+
"No content provided. Please provide content via --content or by piping to stdin.",
|
|
86
|
+
err=True,
|
|
87
|
+
)
|
|
88
|
+
raise typer.Exit(1)
|
|
89
|
+
|
|
90
|
+
# Also check for empty content
|
|
91
|
+
if content is not None and not content.strip():
|
|
92
|
+
typer.echo("Empty content provided. Please provide non-empty content.", err=True)
|
|
93
|
+
raise typer.Exit(1)
|
|
94
|
+
|
|
41
95
|
note = asyncio.run(mcp_write_note(title, content, folder, tags))
|
|
42
96
|
rprint(note)
|
|
43
97
|
except Exception as e: # pragma: no cover
|
|
@@ -79,7 +133,11 @@ def build_context(
|
|
|
79
133
|
max_related=max_related,
|
|
80
134
|
)
|
|
81
135
|
)
|
|
82
|
-
|
|
136
|
+
# Use json module for more controlled serialization
|
|
137
|
+
import json
|
|
138
|
+
|
|
139
|
+
context_dict = context.model_dump(exclude_none=True)
|
|
140
|
+
print(json.dumps(context_dict, indent=2, ensure_ascii=True, default=str))
|
|
83
141
|
except Exception as e: # pragma: no cover
|
|
84
142
|
if not isinstance(e, typer.Exit):
|
|
85
143
|
typer.echo(f"Error during build_context: {e}", err=True)
|
|
@@ -107,7 +165,11 @@ def recent_activity(
|
|
|
107
165
|
max_related=max_related,
|
|
108
166
|
)
|
|
109
167
|
)
|
|
110
|
-
|
|
168
|
+
# Use json module for more controlled serialization
|
|
169
|
+
import json
|
|
170
|
+
|
|
171
|
+
context_dict = context.model_dump(exclude_none=True)
|
|
172
|
+
print(json.dumps(context_dict, indent=2, ensure_ascii=True, default=str))
|
|
111
173
|
except Exception as e: # pragma: no cover
|
|
112
174
|
if not isinstance(e, typer.Exit):
|
|
113
175
|
typer.echo(f"Error during build_context: {e}", err=True)
|
|
@@ -139,7 +201,11 @@ def search(
|
|
|
139
201
|
after_date=after_date,
|
|
140
202
|
)
|
|
141
203
|
results = asyncio.run(mcp_search(query=search_query, page=page, page_size=page_size))
|
|
142
|
-
|
|
204
|
+
# Use json module for more controlled serialization
|
|
205
|
+
import json
|
|
206
|
+
|
|
207
|
+
results_dict = results.model_dump(exclude_none=True)
|
|
208
|
+
print(json.dumps(results_dict, indent=2, ensure_ascii=True, default=str))
|
|
143
209
|
except Exception as e: # pragma: no cover
|
|
144
210
|
if not isinstance(e, typer.Exit):
|
|
145
211
|
logger.exception("Error during search", e)
|
|
@@ -148,18 +214,6 @@ def search(
|
|
|
148
214
|
raise
|
|
149
215
|
|
|
150
216
|
|
|
151
|
-
@tool_app.command()
|
|
152
|
-
def get_entity(identifier: str):
|
|
153
|
-
try:
|
|
154
|
-
entity = asyncio.run(mcp_get_entity(identifier=identifier))
|
|
155
|
-
rprint(entity.model_dump_json(indent=2))
|
|
156
|
-
except Exception as e: # pragma: no cover
|
|
157
|
-
if not isinstance(e, typer.Exit):
|
|
158
|
-
typer.echo(f"Error during get_entity: {e}", err=True)
|
|
159
|
-
raise typer.Exit(1)
|
|
160
|
-
raise
|
|
161
|
-
|
|
162
|
-
|
|
163
217
|
@tool_app.command(name="continue-conversation")
|
|
164
218
|
def continue_conversation(
|
|
165
219
|
topic: Annotated[Optional[str], typer.Option(help="Topic or keyword to search for")] = None,
|
|
@@ -167,7 +221,7 @@ def continue_conversation(
|
|
|
167
221
|
Optional[str], typer.Option(help="How far back to look for activity")
|
|
168
222
|
] = None,
|
|
169
223
|
):
|
|
170
|
-
"""
|
|
224
|
+
"""Prompt to continue a previous conversation or work session."""
|
|
171
225
|
try:
|
|
172
226
|
# Prompt functions return formatted strings directly
|
|
173
227
|
session = asyncio.run(mcp_continue_conversation(topic=topic, timeframe=timeframe))
|
|
@@ -178,3 +232,22 @@ def continue_conversation(
|
|
|
178
232
|
typer.echo(f"Error continuing conversation: {e}", err=True)
|
|
179
233
|
raise typer.Exit(1)
|
|
180
234
|
raise
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
# @tool_app.command(name="show-recent-activity")
|
|
238
|
+
# def show_recent_activity(
|
|
239
|
+
# timeframe: Annotated[
|
|
240
|
+
# str, typer.Option(help="How far back to look for activity")
|
|
241
|
+
# ] = "7d",
|
|
242
|
+
# ):
|
|
243
|
+
# """Prompt to show recent activity."""
|
|
244
|
+
# try:
|
|
245
|
+
# # Prompt functions return formatted strings directly
|
|
246
|
+
# session = asyncio.run(recent_activity_prompt(timeframe=timeframe))
|
|
247
|
+
# rprint(session)
|
|
248
|
+
# except Exception as e: # pragma: no cover
|
|
249
|
+
# if not isinstance(e, typer.Exit):
|
|
250
|
+
# logger.exception("Error continuing conversation", e)
|
|
251
|
+
# typer.echo(f"Error continuing conversation: {e}", err=True)
|
|
252
|
+
# raise typer.Exit(1)
|
|
253
|
+
# raise
|
basic_memory/cli/main.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"""Main CLI entry point for basic-memory.""" # pragma: no cover
|
|
2
2
|
|
|
3
3
|
from basic_memory.cli.app import app # pragma: no cover
|
|
4
|
+
import typer
|
|
4
5
|
|
|
5
6
|
# Register commands
|
|
6
7
|
from basic_memory.cli.commands import ( # noqa: F401 # pragma: no cover
|
|
@@ -12,8 +13,46 @@ from basic_memory.cli.commands import ( # noqa: F401 # pragma: no cover
|
|
|
12
13
|
import_claude_conversations,
|
|
13
14
|
import_claude_projects,
|
|
14
15
|
import_chatgpt,
|
|
15
|
-
|
|
16
|
+
tool,
|
|
17
|
+
project,
|
|
16
18
|
)
|
|
17
19
|
|
|
20
|
+
|
|
21
|
+
# Version command
|
|
22
|
+
@app.callback(invoke_without_command=True)
|
|
23
|
+
def main(
|
|
24
|
+
ctx: typer.Context,
|
|
25
|
+
project: str = typer.Option( # noqa
|
|
26
|
+
"main",
|
|
27
|
+
"--project",
|
|
28
|
+
"-p",
|
|
29
|
+
help="Specify which project to use",
|
|
30
|
+
envvar="BASIC_MEMORY_PROJECT",
|
|
31
|
+
),
|
|
32
|
+
version: bool = typer.Option(
|
|
33
|
+
False,
|
|
34
|
+
"--version",
|
|
35
|
+
"-V",
|
|
36
|
+
help="Show version information and exit.",
|
|
37
|
+
is_eager=True,
|
|
38
|
+
),
|
|
39
|
+
):
|
|
40
|
+
"""Basic Memory - Local-first personal knowledge management system."""
|
|
41
|
+
if version: # pragma: no cover
|
|
42
|
+
from basic_memory import __version__
|
|
43
|
+
from basic_memory.config import config
|
|
44
|
+
|
|
45
|
+
typer.echo(f"Basic Memory v{__version__}")
|
|
46
|
+
typer.echo(f"Current project: {config.project}")
|
|
47
|
+
typer.echo(f"Project path: {config.home}")
|
|
48
|
+
raise typer.Exit()
|
|
49
|
+
|
|
50
|
+
# Handle project selection via environment variable
|
|
51
|
+
if project:
|
|
52
|
+
import os
|
|
53
|
+
|
|
54
|
+
os.environ["BASIC_MEMORY_PROJECT"] = project
|
|
55
|
+
|
|
56
|
+
|
|
18
57
|
if __name__ == "__main__": # pragma: no cover
|
|
19
58
|
app()
|
basic_memory/config.py
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
"""Configuration management for basic-memory."""
|
|
2
2
|
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
3
5
|
from pathlib import Path
|
|
4
|
-
from typing import Literal
|
|
6
|
+
from typing import Any, Dict, Literal, Optional
|
|
5
7
|
|
|
6
8
|
from loguru import logger
|
|
7
9
|
from pydantic import Field, field_validator
|
|
@@ -12,6 +14,7 @@ from basic_memory.utils import setup_logging
|
|
|
12
14
|
|
|
13
15
|
DATABASE_NAME = "memory.db"
|
|
14
16
|
DATA_DIR_NAME = ".basic-memory"
|
|
17
|
+
CONFIG_FILE_NAME = "config.json"
|
|
15
18
|
|
|
16
19
|
Environment = Literal["test", "dev", "user"]
|
|
17
20
|
|
|
@@ -62,15 +65,160 @@ class ProjectConfig(BaseSettings):
|
|
|
62
65
|
return v
|
|
63
66
|
|
|
64
67
|
|
|
65
|
-
|
|
66
|
-
|
|
68
|
+
class BasicMemoryConfig(BaseSettings):
|
|
69
|
+
"""Pydantic model for Basic Memory global configuration."""
|
|
70
|
+
|
|
71
|
+
projects: Dict[str, str] = Field(
|
|
72
|
+
default_factory=lambda: {"main": str(Path.home() / "basic-memory")},
|
|
73
|
+
description="Mapping of project names to their filesystem paths",
|
|
74
|
+
)
|
|
75
|
+
default_project: str = Field(
|
|
76
|
+
default="main",
|
|
77
|
+
description="Name of the default project to use",
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
model_config = SettingsConfigDict(
|
|
81
|
+
env_prefix="BASIC_MEMORY_",
|
|
82
|
+
extra="ignore",
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
def model_post_init(self, __context: Any) -> None:
|
|
86
|
+
"""Ensure configuration is valid after initialization."""
|
|
87
|
+
# Ensure main project exists
|
|
88
|
+
if "main" not in self.projects:
|
|
89
|
+
self.projects["main"] = str(Path.home() / "basic-memory")
|
|
90
|
+
|
|
91
|
+
# Ensure default project is valid
|
|
92
|
+
if self.default_project not in self.projects:
|
|
93
|
+
self.default_project = "main"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class ConfigManager:
|
|
97
|
+
"""Manages Basic Memory configuration."""
|
|
98
|
+
|
|
99
|
+
def __init__(self) -> None:
|
|
100
|
+
"""Initialize the configuration manager."""
|
|
101
|
+
self.config_dir = Path.home() / DATA_DIR_NAME
|
|
102
|
+
self.config_file = self.config_dir / CONFIG_FILE_NAME
|
|
103
|
+
|
|
104
|
+
# Ensure config directory exists
|
|
105
|
+
self.config_dir.mkdir(parents=True, exist_ok=True)
|
|
106
|
+
|
|
107
|
+
# Load or create configuration
|
|
108
|
+
self.config = self.load_config()
|
|
109
|
+
|
|
110
|
+
def load_config(self) -> BasicMemoryConfig:
|
|
111
|
+
"""Load configuration from file or create default."""
|
|
112
|
+
if self.config_file.exists():
|
|
113
|
+
try:
|
|
114
|
+
data = json.loads(self.config_file.read_text())
|
|
115
|
+
return BasicMemoryConfig(**data)
|
|
116
|
+
except Exception as e:
|
|
117
|
+
logger.error(f"Failed to load config: {e}")
|
|
118
|
+
config = BasicMemoryConfig()
|
|
119
|
+
self.save_config(config)
|
|
120
|
+
return config
|
|
121
|
+
else:
|
|
122
|
+
config = BasicMemoryConfig()
|
|
123
|
+
self.save_config(config)
|
|
124
|
+
return config
|
|
125
|
+
|
|
126
|
+
def save_config(self, config: BasicMemoryConfig) -> None:
|
|
127
|
+
"""Save configuration to file."""
|
|
128
|
+
try:
|
|
129
|
+
self.config_file.write_text(json.dumps(config.model_dump(), indent=2))
|
|
130
|
+
except Exception as e: # pragma: no cover
|
|
131
|
+
logger.error(f"Failed to save config: {e}")
|
|
132
|
+
|
|
133
|
+
@property
|
|
134
|
+
def projects(self) -> Dict[str, str]:
|
|
135
|
+
"""Get all configured projects."""
|
|
136
|
+
return self.config.projects.copy()
|
|
137
|
+
|
|
138
|
+
@property
|
|
139
|
+
def default_project(self) -> str:
|
|
140
|
+
"""Get the default project name."""
|
|
141
|
+
return self.config.default_project
|
|
142
|
+
|
|
143
|
+
def get_project_path(self, project_name: Optional[str] = None) -> Path:
|
|
144
|
+
"""Get the path for a specific project or the default project."""
|
|
145
|
+
name = project_name or self.config.default_project
|
|
146
|
+
|
|
147
|
+
# Check if specified in environment variable
|
|
148
|
+
if not project_name and "BASIC_MEMORY_PROJECT" in os.environ:
|
|
149
|
+
name = os.environ["BASIC_MEMORY_PROJECT"]
|
|
150
|
+
|
|
151
|
+
if name not in self.config.projects:
|
|
152
|
+
raise ValueError(f"Project '{name}' not found in configuration")
|
|
153
|
+
|
|
154
|
+
return Path(self.config.projects[name])
|
|
155
|
+
|
|
156
|
+
def add_project(self, name: str, path: str) -> None:
|
|
157
|
+
"""Add a new project to the configuration."""
|
|
158
|
+
if name in self.config.projects:
|
|
159
|
+
raise ValueError(f"Project '{name}' already exists")
|
|
160
|
+
|
|
161
|
+
# Ensure the path exists
|
|
162
|
+
project_path = Path(path)
|
|
163
|
+
project_path.mkdir(parents=True, exist_ok=True)
|
|
164
|
+
|
|
165
|
+
self.config.projects[name] = str(project_path)
|
|
166
|
+
self.save_config(self.config)
|
|
167
|
+
|
|
168
|
+
def remove_project(self, name: str) -> None:
|
|
169
|
+
"""Remove a project from the configuration."""
|
|
170
|
+
if name not in self.config.projects:
|
|
171
|
+
raise ValueError(f"Project '{name}' not found")
|
|
172
|
+
|
|
173
|
+
if name == self.config.default_project:
|
|
174
|
+
raise ValueError(f"Cannot remove the default project '{name}'")
|
|
175
|
+
|
|
176
|
+
del self.config.projects[name]
|
|
177
|
+
self.save_config(self.config)
|
|
178
|
+
|
|
179
|
+
def set_default_project(self, name: str) -> None:
|
|
180
|
+
"""Set the default project."""
|
|
181
|
+
if name not in self.config.projects: # pragma: no cover
|
|
182
|
+
raise ValueError(f"Project '{name}' not found")
|
|
183
|
+
|
|
184
|
+
self.config.default_project = name
|
|
185
|
+
self.save_config(self.config)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def get_project_config(project_name: Optional[str] = None) -> ProjectConfig:
|
|
189
|
+
"""Get a project configuration for the specified project."""
|
|
190
|
+
config_manager = ConfigManager()
|
|
191
|
+
|
|
192
|
+
# Get project name from environment variable or use provided name or default
|
|
193
|
+
actual_project_name = os.environ.get(
|
|
194
|
+
"BASIC_MEMORY_PROJECT", project_name or config_manager.default_project
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
try:
|
|
198
|
+
project_path = config_manager.get_project_path(actual_project_name)
|
|
199
|
+
return ProjectConfig(home=project_path, project=actual_project_name)
|
|
200
|
+
except ValueError: # pragma: no cover
|
|
201
|
+
logger.warning(f"Project '{actual_project_name}' not found, using default")
|
|
202
|
+
project_path = config_manager.get_project_path(config_manager.default_project)
|
|
203
|
+
return ProjectConfig(home=project_path, project=config_manager.default_project)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
# Create config manager
|
|
207
|
+
config_manager = ConfigManager()
|
|
208
|
+
|
|
209
|
+
# Load project config for current context
|
|
210
|
+
config = get_project_config()
|
|
211
|
+
|
|
212
|
+
# setup logging to a single log file in user home directory
|
|
213
|
+
user_home = Path.home()
|
|
214
|
+
log_dir = user_home / DATA_DIR_NAME
|
|
215
|
+
log_dir.mkdir(parents=True, exist_ok=True)
|
|
67
216
|
|
|
68
|
-
# setup logging
|
|
69
217
|
setup_logging(
|
|
70
218
|
env=config.env,
|
|
71
|
-
home_dir=
|
|
219
|
+
home_dir=user_home, # Use user home for logs
|
|
72
220
|
log_level=config.log_level,
|
|
73
|
-
log_file="
|
|
221
|
+
log_file=f"{DATA_DIR_NAME}/basic-memory.log",
|
|
74
222
|
console=False,
|
|
75
223
|
)
|
|
76
|
-
logger.info(f"Starting Basic Memory {basic_memory.__version__}")
|
|
224
|
+
logger.info(f"Starting Basic Memory {basic_memory.__version__} (Project: {config.project})")
|
basic_memory/db.py
CHANGED
|
@@ -86,8 +86,16 @@ async def get_or_create_db(
|
|
|
86
86
|
_engine = create_async_engine(db_url, connect_args={"check_same_thread": False})
|
|
87
87
|
_session_maker = async_sessionmaker(_engine, expire_on_commit=False)
|
|
88
88
|
|
|
89
|
-
|
|
90
|
-
|
|
89
|
+
# These checks should never fail since we just created the engine and session maker
|
|
90
|
+
# if they were None, but we'll check anyway for the type checker
|
|
91
|
+
if _engine is None:
|
|
92
|
+
logger.error("Failed to create database engine", db_path=str(db_path))
|
|
93
|
+
raise RuntimeError("Database engine initialization failed")
|
|
94
|
+
|
|
95
|
+
if _session_maker is None:
|
|
96
|
+
logger.error("Failed to create session maker", db_path=str(db_path))
|
|
97
|
+
raise RuntimeError("Session maker initialization failed")
|
|
98
|
+
|
|
91
99
|
return _engine, _session_maker
|
|
92
100
|
|
|
93
101
|
|
|
@@ -121,8 +129,15 @@ async def engine_session_factory(
|
|
|
121
129
|
try:
|
|
122
130
|
_session_maker = async_sessionmaker(_engine, expire_on_commit=False)
|
|
123
131
|
|
|
124
|
-
|
|
125
|
-
|
|
132
|
+
# Verify that engine and session maker are initialized
|
|
133
|
+
if _engine is None: # pragma: no cover
|
|
134
|
+
logger.error("Database engine is None in engine_session_factory")
|
|
135
|
+
raise RuntimeError("Database engine initialization failed")
|
|
136
|
+
|
|
137
|
+
if _session_maker is None: # pragma: no cover
|
|
138
|
+
logger.error("Session maker is None in engine_session_factory")
|
|
139
|
+
raise RuntimeError("Session maker initialization failed")
|
|
140
|
+
|
|
126
141
|
yield _engine, _session_maker
|
|
127
142
|
finally:
|
|
128
143
|
if _engine:
|
basic_memory/deps.py
CHANGED
|
@@ -2,7 +2,6 @@
|
|
|
2
2
|
|
|
3
3
|
from typing import Annotated
|
|
4
4
|
|
|
5
|
-
import logfire
|
|
6
5
|
from fastapi import Depends
|
|
7
6
|
from sqlalchemy.ext.asyncio import (
|
|
8
7
|
AsyncSession,
|
|
@@ -16,6 +15,7 @@ from basic_memory.markdown import EntityParser
|
|
|
16
15
|
from basic_memory.markdown.markdown_processor import MarkdownProcessor
|
|
17
16
|
from basic_memory.repository.entity_repository import EntityRepository
|
|
18
17
|
from basic_memory.repository.observation_repository import ObservationRepository
|
|
18
|
+
from basic_memory.repository.project_info_repository import ProjectInfoRepository
|
|
19
19
|
from basic_memory.repository.relation_repository import RelationRepository
|
|
20
20
|
from basic_memory.repository.search_repository import SearchRepository
|
|
21
21
|
from basic_memory.services import (
|
|
@@ -45,8 +45,6 @@ async def get_engine_factory(
|
|
|
45
45
|
) -> tuple[AsyncEngine, async_sessionmaker[AsyncSession]]: # pragma: no cover
|
|
46
46
|
"""Get engine and session maker."""
|
|
47
47
|
engine, session_maker = await db.get_or_create_db(project_config.database_path)
|
|
48
|
-
if project_config.env != "test":
|
|
49
|
-
logfire.instrument_sqlalchemy(engine=engine)
|
|
50
48
|
return engine, session_maker
|
|
51
49
|
|
|
52
50
|
|
|
@@ -107,6 +105,15 @@ async def get_search_repository(
|
|
|
107
105
|
SearchRepositoryDep = Annotated[SearchRepository, Depends(get_search_repository)]
|
|
108
106
|
|
|
109
107
|
|
|
108
|
+
def get_project_info_repository(
|
|
109
|
+
session_maker: SessionMakerDep,
|
|
110
|
+
):
|
|
111
|
+
"""Dependency for StatsRepository."""
|
|
112
|
+
return ProjectInfoRepository(session_maker)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
ProjectInfoRepositoryDep = Annotated[ProjectInfoRepository, Depends(get_project_info_repository)]
|
|
116
|
+
|
|
110
117
|
## services
|
|
111
118
|
|
|
112
119
|
|