basic-memory 0.16.1__py3-none-any.whl → 0.17.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of basic-memory might be problematic. Click here for more details.
- basic_memory/__init__.py +1 -1
- basic_memory/alembic/env.py +112 -26
- basic_memory/alembic/versions/314f1ea54dc4_add_postgres_full_text_search_support_.py +131 -0
- basic_memory/alembic/versions/5fe1ab1ccebe_add_projects_table.py +15 -3
- basic_memory/alembic/versions/647e7a75e2cd_project_constraint_fix.py +44 -36
- basic_memory/alembic/versions/6830751f5fb6_merge_multiple_heads.py +24 -0
- basic_memory/alembic/versions/a2b3c4d5e6f7_add_search_index_entity_cascade.py +56 -0
- basic_memory/alembic/versions/cc7172b46608_update_search_index_schema.py +13 -0
- basic_memory/alembic/versions/f8a9b2c3d4e5_add_pg_trgm_for_fuzzy_link_resolution.py +239 -0
- basic_memory/alembic/versions/g9a0b3c4d5e6_add_external_id_to_project_and_entity.py +173 -0
- basic_memory/api/app.py +45 -24
- basic_memory/api/container.py +133 -0
- basic_memory/api/routers/knowledge_router.py +17 -5
- basic_memory/api/routers/project_router.py +68 -14
- basic_memory/api/routers/resource_router.py +37 -27
- basic_memory/api/routers/utils.py +53 -14
- basic_memory/api/v2/__init__.py +35 -0
- basic_memory/api/v2/routers/__init__.py +21 -0
- basic_memory/api/v2/routers/directory_router.py +93 -0
- basic_memory/api/v2/routers/importer_router.py +181 -0
- basic_memory/api/v2/routers/knowledge_router.py +427 -0
- basic_memory/api/v2/routers/memory_router.py +130 -0
- basic_memory/api/v2/routers/project_router.py +359 -0
- basic_memory/api/v2/routers/prompt_router.py +269 -0
- basic_memory/api/v2/routers/resource_router.py +286 -0
- basic_memory/api/v2/routers/search_router.py +73 -0
- basic_memory/cli/app.py +43 -7
- basic_memory/cli/auth.py +27 -4
- basic_memory/cli/commands/__init__.py +3 -1
- basic_memory/cli/commands/cloud/api_client.py +20 -5
- basic_memory/cli/commands/cloud/cloud_utils.py +13 -6
- basic_memory/cli/commands/cloud/rclone_commands.py +110 -14
- basic_memory/cli/commands/cloud/rclone_installer.py +18 -4
- basic_memory/cli/commands/cloud/upload.py +10 -3
- basic_memory/cli/commands/command_utils.py +52 -4
- basic_memory/cli/commands/db.py +78 -19
- basic_memory/cli/commands/format.py +198 -0
- basic_memory/cli/commands/import_chatgpt.py +12 -8
- basic_memory/cli/commands/import_claude_conversations.py +12 -8
- basic_memory/cli/commands/import_claude_projects.py +12 -8
- basic_memory/cli/commands/import_memory_json.py +12 -8
- basic_memory/cli/commands/mcp.py +8 -26
- basic_memory/cli/commands/project.py +22 -9
- basic_memory/cli/commands/status.py +3 -2
- basic_memory/cli/commands/telemetry.py +81 -0
- basic_memory/cli/container.py +84 -0
- basic_memory/cli/main.py +7 -0
- basic_memory/config.py +177 -77
- basic_memory/db.py +183 -77
- basic_memory/deps/__init__.py +293 -0
- basic_memory/deps/config.py +26 -0
- basic_memory/deps/db.py +56 -0
- basic_memory/deps/importers.py +200 -0
- basic_memory/deps/projects.py +238 -0
- basic_memory/deps/repositories.py +179 -0
- basic_memory/deps/services.py +480 -0
- basic_memory/deps.py +14 -409
- basic_memory/file_utils.py +212 -3
- basic_memory/ignore_utils.py +5 -5
- basic_memory/importers/base.py +40 -19
- basic_memory/importers/chatgpt_importer.py +17 -4
- basic_memory/importers/claude_conversations_importer.py +27 -12
- basic_memory/importers/claude_projects_importer.py +50 -14
- basic_memory/importers/memory_json_importer.py +36 -16
- basic_memory/importers/utils.py +5 -2
- basic_memory/markdown/entity_parser.py +62 -23
- basic_memory/markdown/markdown_processor.py +67 -4
- basic_memory/markdown/plugins.py +4 -2
- basic_memory/markdown/utils.py +10 -1
- basic_memory/mcp/async_client.py +1 -0
- basic_memory/mcp/clients/__init__.py +28 -0
- basic_memory/mcp/clients/directory.py +70 -0
- basic_memory/mcp/clients/knowledge.py +176 -0
- basic_memory/mcp/clients/memory.py +120 -0
- basic_memory/mcp/clients/project.py +89 -0
- basic_memory/mcp/clients/resource.py +71 -0
- basic_memory/mcp/clients/search.py +65 -0
- basic_memory/mcp/container.py +110 -0
- basic_memory/mcp/project_context.py +47 -33
- basic_memory/mcp/prompts/ai_assistant_guide.py +2 -2
- basic_memory/mcp/prompts/recent_activity.py +2 -2
- basic_memory/mcp/prompts/utils.py +3 -3
- basic_memory/mcp/server.py +58 -0
- basic_memory/mcp/tools/build_context.py +14 -14
- basic_memory/mcp/tools/canvas.py +34 -12
- basic_memory/mcp/tools/chatgpt_tools.py +4 -1
- basic_memory/mcp/tools/delete_note.py +31 -7
- basic_memory/mcp/tools/edit_note.py +14 -9
- basic_memory/mcp/tools/list_directory.py +7 -17
- basic_memory/mcp/tools/move_note.py +35 -31
- basic_memory/mcp/tools/project_management.py +29 -25
- basic_memory/mcp/tools/read_content.py +13 -3
- basic_memory/mcp/tools/read_note.py +24 -14
- basic_memory/mcp/tools/recent_activity.py +32 -38
- basic_memory/mcp/tools/search.py +17 -10
- basic_memory/mcp/tools/utils.py +28 -0
- basic_memory/mcp/tools/view_note.py +2 -1
- basic_memory/mcp/tools/write_note.py +37 -14
- basic_memory/models/knowledge.py +15 -2
- basic_memory/models/project.py +7 -1
- basic_memory/models/search.py +58 -2
- basic_memory/project_resolver.py +222 -0
- basic_memory/repository/entity_repository.py +210 -3
- basic_memory/repository/observation_repository.py +1 -0
- basic_memory/repository/postgres_search_repository.py +451 -0
- basic_memory/repository/project_repository.py +38 -1
- basic_memory/repository/relation_repository.py +58 -2
- basic_memory/repository/repository.py +1 -0
- basic_memory/repository/search_index_row.py +95 -0
- basic_memory/repository/search_repository.py +77 -615
- basic_memory/repository/search_repository_base.py +241 -0
- basic_memory/repository/sqlite_search_repository.py +437 -0
- basic_memory/runtime.py +61 -0
- basic_memory/schemas/base.py +36 -6
- basic_memory/schemas/directory.py +2 -1
- basic_memory/schemas/memory.py +9 -2
- basic_memory/schemas/project_info.py +2 -0
- basic_memory/schemas/response.py +84 -27
- basic_memory/schemas/search.py +5 -0
- basic_memory/schemas/sync_report.py +1 -1
- basic_memory/schemas/v2/__init__.py +27 -0
- basic_memory/schemas/v2/entity.py +133 -0
- basic_memory/schemas/v2/resource.py +47 -0
- basic_memory/services/context_service.py +219 -43
- basic_memory/services/directory_service.py +26 -11
- basic_memory/services/entity_service.py +68 -33
- basic_memory/services/file_service.py +131 -16
- basic_memory/services/initialization.py +51 -26
- basic_memory/services/link_resolver.py +1 -0
- basic_memory/services/project_service.py +68 -43
- basic_memory/services/search_service.py +75 -16
- basic_memory/sync/__init__.py +2 -1
- basic_memory/sync/coordinator.py +160 -0
- basic_memory/sync/sync_service.py +135 -115
- basic_memory/sync/watch_service.py +32 -12
- basic_memory/telemetry.py +249 -0
- basic_memory/utils.py +96 -75
- {basic_memory-0.16.1.dist-info → basic_memory-0.17.4.dist-info}/METADATA +129 -5
- basic_memory-0.17.4.dist-info/RECORD +193 -0
- {basic_memory-0.16.1.dist-info → basic_memory-0.17.4.dist-info}/WHEEL +1 -1
- basic_memory-0.16.1.dist-info/RECORD +0 -148
- {basic_memory-0.16.1.dist-info → basic_memory-0.17.4.dist-info}/entry_points.txt +0 -0
- {basic_memory-0.16.1.dist-info → basic_memory-0.17.4.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""V2 Import Router - ID-based data import operations.
|
|
2
|
+
|
|
3
|
+
This router uses v2 dependencies for consistent project handling with external_id UUIDs.
|
|
4
|
+
Import endpoints use project_id in the path for consistency with other v2 endpoints.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
|
|
10
|
+
from fastapi import APIRouter, Form, HTTPException, UploadFile, status, Path
|
|
11
|
+
|
|
12
|
+
from basic_memory.deps import (
|
|
13
|
+
ChatGPTImporterV2ExternalDep,
|
|
14
|
+
ClaudeConversationsImporterV2ExternalDep,
|
|
15
|
+
ClaudeProjectsImporterV2ExternalDep,
|
|
16
|
+
MemoryJsonImporterV2ExternalDep,
|
|
17
|
+
)
|
|
18
|
+
from basic_memory.importers import Importer
|
|
19
|
+
from basic_memory.schemas.importer import (
|
|
20
|
+
ChatImportResult,
|
|
21
|
+
EntityImportResult,
|
|
22
|
+
ProjectImportResult,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
router = APIRouter(prefix="/import", tags=["import-v2"])
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@router.post("/chatgpt", response_model=ChatImportResult)
|
|
31
|
+
async def import_chatgpt(
|
|
32
|
+
importer: ChatGPTImporterV2ExternalDep,
|
|
33
|
+
file: UploadFile,
|
|
34
|
+
project_id: str = Path(..., description="Project external UUID"),
|
|
35
|
+
folder: str = Form("conversations"),
|
|
36
|
+
) -> ChatImportResult:
|
|
37
|
+
"""Import conversations from ChatGPT JSON export.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
project_id: Project external UUID from URL path
|
|
41
|
+
file: The ChatGPT conversations.json file.
|
|
42
|
+
folder: The folder to place the files in.
|
|
43
|
+
importer: ChatGPT importer instance.
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
ChatImportResult with import statistics.
|
|
47
|
+
|
|
48
|
+
Raises:
|
|
49
|
+
HTTPException: If import fails.
|
|
50
|
+
"""
|
|
51
|
+
logger.info(f"V2 Importing ChatGPT conversations for project {project_id}")
|
|
52
|
+
return await import_file(importer, file, folder)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@router.post("/claude/conversations", response_model=ChatImportResult)
|
|
56
|
+
async def import_claude_conversations(
|
|
57
|
+
importer: ClaudeConversationsImporterV2ExternalDep,
|
|
58
|
+
file: UploadFile,
|
|
59
|
+
project_id: str = Path(..., description="Project external UUID"),
|
|
60
|
+
folder: str = Form("conversations"),
|
|
61
|
+
) -> ChatImportResult:
|
|
62
|
+
"""Import conversations from Claude conversations.json export.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
project_id: Project external UUID from URL path
|
|
66
|
+
file: The Claude conversations.json file.
|
|
67
|
+
folder: The folder to place the files in.
|
|
68
|
+
importer: Claude conversations importer instance.
|
|
69
|
+
|
|
70
|
+
Returns:
|
|
71
|
+
ChatImportResult with import statistics.
|
|
72
|
+
|
|
73
|
+
Raises:
|
|
74
|
+
HTTPException: If import fails.
|
|
75
|
+
"""
|
|
76
|
+
logger.info(f"V2 Importing Claude conversations for project {project_id}")
|
|
77
|
+
return await import_file(importer, file, folder)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@router.post("/claude/projects", response_model=ProjectImportResult)
|
|
81
|
+
async def import_claude_projects(
|
|
82
|
+
importer: ClaudeProjectsImporterV2ExternalDep,
|
|
83
|
+
file: UploadFile,
|
|
84
|
+
project_id: str = Path(..., description="Project external UUID"),
|
|
85
|
+
folder: str = Form("projects"),
|
|
86
|
+
) -> ProjectImportResult:
|
|
87
|
+
"""Import projects from Claude projects.json export.
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
project_id: Project external UUID from URL path
|
|
91
|
+
file: The Claude projects.json file.
|
|
92
|
+
folder: The base folder to place the files in.
|
|
93
|
+
importer: Claude projects importer instance.
|
|
94
|
+
|
|
95
|
+
Returns:
|
|
96
|
+
ProjectImportResult with import statistics.
|
|
97
|
+
|
|
98
|
+
Raises:
|
|
99
|
+
HTTPException: If import fails.
|
|
100
|
+
"""
|
|
101
|
+
logger.info(f"V2 Importing Claude projects for project {project_id}")
|
|
102
|
+
return await import_file(importer, file, folder)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@router.post("/memory-json", response_model=EntityImportResult)
|
|
106
|
+
async def import_memory_json(
|
|
107
|
+
importer: MemoryJsonImporterV2ExternalDep,
|
|
108
|
+
file: UploadFile,
|
|
109
|
+
project_id: str = Path(..., description="Project external UUID"),
|
|
110
|
+
folder: str = Form("conversations"),
|
|
111
|
+
) -> EntityImportResult:
|
|
112
|
+
"""Import entities and relations from a memory.json file.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
project_id: Project external UUID from URL path
|
|
116
|
+
file: The memory.json file.
|
|
117
|
+
folder: Optional destination folder within the project.
|
|
118
|
+
importer: Memory JSON importer instance.
|
|
119
|
+
|
|
120
|
+
Returns:
|
|
121
|
+
EntityImportResult with import statistics.
|
|
122
|
+
|
|
123
|
+
Raises:
|
|
124
|
+
HTTPException: If import fails.
|
|
125
|
+
"""
|
|
126
|
+
logger.info(f"V2 Importing memory.json for project {project_id}")
|
|
127
|
+
try:
|
|
128
|
+
file_data = []
|
|
129
|
+
file_bytes = await file.read()
|
|
130
|
+
file_str = file_bytes.decode("utf-8")
|
|
131
|
+
for line in file_str.splitlines():
|
|
132
|
+
json_data = json.loads(line)
|
|
133
|
+
file_data.append(json_data)
|
|
134
|
+
|
|
135
|
+
result = await importer.import_data(file_data, folder)
|
|
136
|
+
if not result.success: # pragma: no cover
|
|
137
|
+
raise HTTPException(
|
|
138
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
139
|
+
detail=result.error_message or "Import failed",
|
|
140
|
+
)
|
|
141
|
+
except Exception as e:
|
|
142
|
+
logger.exception("V2 Import failed")
|
|
143
|
+
raise HTTPException(
|
|
144
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
145
|
+
detail=f"Import failed: {str(e)}",
|
|
146
|
+
)
|
|
147
|
+
return result
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
async def import_file(importer: Importer, file: UploadFile, destination_folder: str):
|
|
151
|
+
"""Helper function to import a file using an importer instance.
|
|
152
|
+
|
|
153
|
+
Args:
|
|
154
|
+
importer: The importer instance to use
|
|
155
|
+
file: The file to import
|
|
156
|
+
destination_folder: Destination folder for imported content
|
|
157
|
+
|
|
158
|
+
Returns:
|
|
159
|
+
Import result from the importer
|
|
160
|
+
|
|
161
|
+
Raises:
|
|
162
|
+
HTTPException: If import fails
|
|
163
|
+
"""
|
|
164
|
+
try:
|
|
165
|
+
# Process file
|
|
166
|
+
json_data = json.load(file.file)
|
|
167
|
+
result = await importer.import_data(json_data, destination_folder)
|
|
168
|
+
if not result.success: # pragma: no cover
|
|
169
|
+
raise HTTPException(
|
|
170
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
171
|
+
detail=result.error_message or "Import failed",
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
return result
|
|
175
|
+
|
|
176
|
+
except Exception as e:
|
|
177
|
+
logger.exception("V2 Import failed")
|
|
178
|
+
raise HTTPException(
|
|
179
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
180
|
+
detail=f"Import failed: {str(e)}",
|
|
181
|
+
)
|
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
"""V2 Knowledge Router - External ID-based entity operations.
|
|
2
|
+
|
|
3
|
+
This router provides external_id (UUID) based CRUD operations for entities,
|
|
4
|
+
using stable string UUIDs that won't change with file moves or database migrations.
|
|
5
|
+
|
|
6
|
+
Key improvements:
|
|
7
|
+
- Stable external UUIDs that won't change with file moves or renames
|
|
8
|
+
- Better API ergonomics with consistent string identifiers
|
|
9
|
+
- Direct database lookups via unique indexed column
|
|
10
|
+
- Simplified caching strategies
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Response, Path
|
|
14
|
+
from loguru import logger
|
|
15
|
+
|
|
16
|
+
from basic_memory.deps import (
|
|
17
|
+
EntityServiceV2ExternalDep,
|
|
18
|
+
SearchServiceV2ExternalDep,
|
|
19
|
+
LinkResolverV2ExternalDep,
|
|
20
|
+
ProjectConfigV2ExternalDep,
|
|
21
|
+
AppConfigDep,
|
|
22
|
+
SyncServiceV2ExternalDep,
|
|
23
|
+
EntityRepositoryV2ExternalDep,
|
|
24
|
+
ProjectExternalIdPathDep,
|
|
25
|
+
)
|
|
26
|
+
from basic_memory.schemas import DeleteEntitiesResponse
|
|
27
|
+
from basic_memory.schemas.base import Entity
|
|
28
|
+
from basic_memory.schemas.request import EditEntityRequest
|
|
29
|
+
from basic_memory.schemas.v2 import (
|
|
30
|
+
EntityResolveRequest,
|
|
31
|
+
EntityResolveResponse,
|
|
32
|
+
EntityResponseV2,
|
|
33
|
+
MoveEntityRequestV2,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
router = APIRouter(prefix="/knowledge", tags=["knowledge-v2"])
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
async def resolve_relations_background(sync_service, entity_id: int, entity_permalink: str) -> None:
|
|
40
|
+
"""Background task to resolve relations for a specific entity.
|
|
41
|
+
|
|
42
|
+
This runs asynchronously after the API response is sent, preventing
|
|
43
|
+
long delays when creating entities with many relations.
|
|
44
|
+
"""
|
|
45
|
+
try: # pragma: no cover
|
|
46
|
+
# Only resolve relations for the newly created entity
|
|
47
|
+
await sync_service.resolve_relations(entity_id=entity_id) # pragma: no cover
|
|
48
|
+
logger.debug( # pragma: no cover
|
|
49
|
+
f"Background: Resolved relations for entity {entity_permalink} (id={entity_id})"
|
|
50
|
+
)
|
|
51
|
+
except Exception as e: # pragma: no cover
|
|
52
|
+
# Log but don't fail - this is a background task
|
|
53
|
+
logger.warning( # pragma: no cover
|
|
54
|
+
f"Background: Failed to resolve relations for entity {entity_permalink}: {e}"
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
## Resolution endpoint
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@router.post("/resolve", response_model=EntityResolveResponse)
|
|
62
|
+
async def resolve_identifier(
|
|
63
|
+
project_id: ProjectExternalIdPathDep,
|
|
64
|
+
data: EntityResolveRequest,
|
|
65
|
+
link_resolver: LinkResolverV2ExternalDep,
|
|
66
|
+
entity_repository: EntityRepositoryV2ExternalDep,
|
|
67
|
+
) -> EntityResolveResponse:
|
|
68
|
+
"""Resolve a string identifier (external_id, permalink, title, or path) to entity info.
|
|
69
|
+
|
|
70
|
+
This endpoint provides a bridge between v1-style identifiers and v2 external_ids.
|
|
71
|
+
Use this to convert existing references to the new UUID-based format.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
data: Request containing the identifier to resolve
|
|
75
|
+
|
|
76
|
+
Returns:
|
|
77
|
+
Entity external_id and metadata about how it was resolved
|
|
78
|
+
|
|
79
|
+
Raises:
|
|
80
|
+
HTTPException: 404 if identifier cannot be resolved
|
|
81
|
+
|
|
82
|
+
Example:
|
|
83
|
+
POST /v2/{project_id}/knowledge/resolve
|
|
84
|
+
{"identifier": "specs/search"}
|
|
85
|
+
|
|
86
|
+
Returns:
|
|
87
|
+
{
|
|
88
|
+
"external_id": "550e8400-e29b-41d4-a716-446655440000",
|
|
89
|
+
"entity_id": 123,
|
|
90
|
+
"permalink": "specs/search",
|
|
91
|
+
"file_path": "specs/search.md",
|
|
92
|
+
"title": "Search Specification",
|
|
93
|
+
"resolution_method": "permalink"
|
|
94
|
+
}
|
|
95
|
+
"""
|
|
96
|
+
logger.info(f"API v2 request: resolve_identifier for '{data.identifier}'")
|
|
97
|
+
|
|
98
|
+
# Try to resolve by external_id first
|
|
99
|
+
entity = await entity_repository.get_by_external_id(data.identifier)
|
|
100
|
+
resolution_method = "external_id" if entity else "search"
|
|
101
|
+
|
|
102
|
+
# If not found by external_id, try other resolution methods
|
|
103
|
+
if not entity:
|
|
104
|
+
entity = await link_resolver.resolve_link(data.identifier)
|
|
105
|
+
if entity:
|
|
106
|
+
# Determine resolution method
|
|
107
|
+
if entity.permalink == data.identifier:
|
|
108
|
+
resolution_method = "permalink"
|
|
109
|
+
elif entity.title == data.identifier:
|
|
110
|
+
resolution_method = "title"
|
|
111
|
+
elif entity.file_path == data.identifier:
|
|
112
|
+
resolution_method = "path"
|
|
113
|
+
else:
|
|
114
|
+
resolution_method = "search"
|
|
115
|
+
|
|
116
|
+
if not entity:
|
|
117
|
+
raise HTTPException(status_code=404, detail=f"Entity not found: '{data.identifier}'")
|
|
118
|
+
|
|
119
|
+
result = EntityResolveResponse(
|
|
120
|
+
external_id=entity.external_id,
|
|
121
|
+
entity_id=entity.id,
|
|
122
|
+
permalink=entity.permalink,
|
|
123
|
+
file_path=entity.file_path,
|
|
124
|
+
title=entity.title,
|
|
125
|
+
resolution_method=resolution_method,
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
logger.info(
|
|
129
|
+
f"API v2 response: resolved '{data.identifier}' to external_id={result.external_id} via {resolution_method}"
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
return result
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
## Read endpoints
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@router.get("/entities/{entity_id}", response_model=EntityResponseV2)
|
|
139
|
+
async def get_entity_by_id(
|
|
140
|
+
project_id: ProjectExternalIdPathDep,
|
|
141
|
+
entity_repository: EntityRepositoryV2ExternalDep,
|
|
142
|
+
entity_id: str = Path(..., description="Entity external ID (UUID)"),
|
|
143
|
+
) -> EntityResponseV2:
|
|
144
|
+
"""Get an entity by its external ID (UUID).
|
|
145
|
+
|
|
146
|
+
This is the primary entity retrieval method in v2, using stable UUID
|
|
147
|
+
identifiers that won't change with file moves.
|
|
148
|
+
|
|
149
|
+
Args:
|
|
150
|
+
entity_id: External ID (UUID string)
|
|
151
|
+
|
|
152
|
+
Returns:
|
|
153
|
+
Complete entity with observations and relations
|
|
154
|
+
|
|
155
|
+
Raises:
|
|
156
|
+
HTTPException: 404 if entity not found
|
|
157
|
+
"""
|
|
158
|
+
logger.info(f"API v2 request: get_entity_by_id entity_id={entity_id}")
|
|
159
|
+
|
|
160
|
+
entity = await entity_repository.get_by_external_id(entity_id)
|
|
161
|
+
if not entity:
|
|
162
|
+
raise HTTPException(
|
|
163
|
+
status_code=404, detail=f"Entity with external_id '{entity_id}' not found"
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
result = EntityResponseV2.model_validate(entity)
|
|
167
|
+
logger.info(f"API v2 response: external_id={entity_id}, title='{result.title}'")
|
|
168
|
+
|
|
169
|
+
return result
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
## Create endpoints
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@router.post("/entities", response_model=EntityResponseV2)
|
|
176
|
+
async def create_entity(
|
|
177
|
+
project_id: ProjectExternalIdPathDep,
|
|
178
|
+
data: Entity,
|
|
179
|
+
background_tasks: BackgroundTasks,
|
|
180
|
+
entity_service: EntityServiceV2ExternalDep,
|
|
181
|
+
search_service: SearchServiceV2ExternalDep,
|
|
182
|
+
) -> EntityResponseV2:
|
|
183
|
+
"""Create a new entity.
|
|
184
|
+
|
|
185
|
+
Args:
|
|
186
|
+
data: Entity data to create
|
|
187
|
+
|
|
188
|
+
Returns:
|
|
189
|
+
Created entity with generated external_id (UUID)
|
|
190
|
+
"""
|
|
191
|
+
logger.info(
|
|
192
|
+
"API v2 request", endpoint="create_entity", entity_type=data.entity_type, title=data.title
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
entity = await entity_service.create_entity(data)
|
|
196
|
+
|
|
197
|
+
# reindex
|
|
198
|
+
await search_service.index_entity(entity, background_tasks=background_tasks)
|
|
199
|
+
result = EntityResponseV2.model_validate(entity)
|
|
200
|
+
|
|
201
|
+
logger.info(
|
|
202
|
+
f"API v2 response: endpoint='create_entity' external_id={entity.external_id}, title={result.title}, permalink={result.permalink}, status_code=201"
|
|
203
|
+
)
|
|
204
|
+
return result
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
## Update endpoints
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
@router.put("/entities/{entity_id}", response_model=EntityResponseV2)
|
|
211
|
+
async def update_entity_by_id(
|
|
212
|
+
data: Entity,
|
|
213
|
+
response: Response,
|
|
214
|
+
background_tasks: BackgroundTasks,
|
|
215
|
+
project_id: ProjectExternalIdPathDep,
|
|
216
|
+
entity_service: EntityServiceV2ExternalDep,
|
|
217
|
+
search_service: SearchServiceV2ExternalDep,
|
|
218
|
+
sync_service: SyncServiceV2ExternalDep,
|
|
219
|
+
entity_repository: EntityRepositoryV2ExternalDep,
|
|
220
|
+
entity_id: str = Path(..., description="Entity external ID (UUID)"),
|
|
221
|
+
) -> EntityResponseV2:
|
|
222
|
+
"""Update an entity by external ID.
|
|
223
|
+
|
|
224
|
+
If the entity doesn't exist, it will be created (upsert behavior).
|
|
225
|
+
|
|
226
|
+
Args:
|
|
227
|
+
entity_id: External ID (UUID string)
|
|
228
|
+
data: Updated entity data
|
|
229
|
+
|
|
230
|
+
Returns:
|
|
231
|
+
Updated entity
|
|
232
|
+
"""
|
|
233
|
+
logger.info(f"API v2 request: update_entity_by_id entity_id={entity_id}")
|
|
234
|
+
|
|
235
|
+
# Check if entity exists
|
|
236
|
+
existing = await entity_repository.get_by_external_id(entity_id)
|
|
237
|
+
created = existing is None
|
|
238
|
+
|
|
239
|
+
# Perform update or create
|
|
240
|
+
entity, _ = await entity_service.create_or_update_entity(data)
|
|
241
|
+
response.status_code = 201 if created else 200
|
|
242
|
+
|
|
243
|
+
# reindex
|
|
244
|
+
await search_service.index_entity(entity, background_tasks=background_tasks)
|
|
245
|
+
|
|
246
|
+
# Schedule relation resolution for new entities
|
|
247
|
+
if created:
|
|
248
|
+
background_tasks.add_task( # pragma: no cover
|
|
249
|
+
resolve_relations_background, sync_service, entity.id, entity.permalink or ""
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
result = EntityResponseV2.model_validate(entity)
|
|
253
|
+
|
|
254
|
+
logger.info(
|
|
255
|
+
f"API v2 response: external_id={entity_id}, created={created}, status_code={response.status_code}"
|
|
256
|
+
)
|
|
257
|
+
return result
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
@router.patch("/entities/{entity_id}", response_model=EntityResponseV2)
|
|
261
|
+
async def edit_entity_by_id(
|
|
262
|
+
data: EditEntityRequest,
|
|
263
|
+
background_tasks: BackgroundTasks,
|
|
264
|
+
project_id: ProjectExternalIdPathDep,
|
|
265
|
+
entity_service: EntityServiceV2ExternalDep,
|
|
266
|
+
search_service: SearchServiceV2ExternalDep,
|
|
267
|
+
entity_repository: EntityRepositoryV2ExternalDep,
|
|
268
|
+
entity_id: str = Path(..., description="Entity external ID (UUID)"),
|
|
269
|
+
) -> EntityResponseV2:
|
|
270
|
+
"""Edit an existing entity by external ID using operations like append, prepend, etc.
|
|
271
|
+
|
|
272
|
+
Args:
|
|
273
|
+
entity_id: External ID (UUID string)
|
|
274
|
+
data: Edit operation details
|
|
275
|
+
|
|
276
|
+
Returns:
|
|
277
|
+
Updated entity
|
|
278
|
+
|
|
279
|
+
Raises:
|
|
280
|
+
HTTPException: 404 if entity not found, 400 if edit fails
|
|
281
|
+
"""
|
|
282
|
+
logger.info(
|
|
283
|
+
f"API v2 request: edit_entity_by_id entity_id={entity_id}, operation='{data.operation}'"
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
# Verify entity exists
|
|
287
|
+
entity = await entity_repository.get_by_external_id(entity_id)
|
|
288
|
+
if not entity: # pragma: no cover
|
|
289
|
+
raise HTTPException(
|
|
290
|
+
status_code=404, detail=f"Entity with external_id '{entity_id}' not found"
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
try:
|
|
294
|
+
# Edit using the entity's permalink or path
|
|
295
|
+
identifier = entity.permalink or entity.file_path
|
|
296
|
+
updated_entity = await entity_service.edit_entity(
|
|
297
|
+
identifier=identifier,
|
|
298
|
+
operation=data.operation,
|
|
299
|
+
content=data.content,
|
|
300
|
+
section=data.section,
|
|
301
|
+
find_text=data.find_text,
|
|
302
|
+
expected_replacements=data.expected_replacements,
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
# Reindex
|
|
306
|
+
await search_service.index_entity(updated_entity, background_tasks=background_tasks)
|
|
307
|
+
|
|
308
|
+
result = EntityResponseV2.model_validate(updated_entity)
|
|
309
|
+
|
|
310
|
+
logger.info(
|
|
311
|
+
f"API v2 response: external_id={entity_id}, operation='{data.operation}', status_code=200"
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
return result
|
|
315
|
+
|
|
316
|
+
except Exception as e:
|
|
317
|
+
logger.error(f"Error editing entity {entity_id}: {e}")
|
|
318
|
+
raise HTTPException(status_code=400, detail=str(e))
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
## Delete endpoints
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
@router.delete("/entities/{entity_id}", response_model=DeleteEntitiesResponse)
|
|
325
|
+
async def delete_entity_by_id(
|
|
326
|
+
background_tasks: BackgroundTasks,
|
|
327
|
+
project_id: ProjectExternalIdPathDep,
|
|
328
|
+
entity_service: EntityServiceV2ExternalDep,
|
|
329
|
+
entity_repository: EntityRepositoryV2ExternalDep,
|
|
330
|
+
entity_id: str = Path(..., description="Entity external ID (UUID)"),
|
|
331
|
+
search_service=Depends(lambda: None), # Optional for now
|
|
332
|
+
) -> DeleteEntitiesResponse:
|
|
333
|
+
"""Delete an entity by external ID.
|
|
334
|
+
|
|
335
|
+
Args:
|
|
336
|
+
entity_id: External ID (UUID string)
|
|
337
|
+
|
|
338
|
+
Returns:
|
|
339
|
+
Deletion status
|
|
340
|
+
|
|
341
|
+
Note: Returns deleted=False if entity doesn't exist (idempotent)
|
|
342
|
+
"""
|
|
343
|
+
logger.info(f"API v2 request: delete_entity_by_id entity_id={entity_id}")
|
|
344
|
+
|
|
345
|
+
entity = await entity_repository.get_by_external_id(entity_id)
|
|
346
|
+
if entity is None:
|
|
347
|
+
logger.info(f"API v2 response: external_id={entity_id} not found, deleted=False")
|
|
348
|
+
return DeleteEntitiesResponse(deleted=False)
|
|
349
|
+
|
|
350
|
+
# Delete the entity using internal ID
|
|
351
|
+
deleted = await entity_service.delete_entity(entity.id)
|
|
352
|
+
|
|
353
|
+
# Remove from search index if search service available
|
|
354
|
+
if search_service:
|
|
355
|
+
background_tasks.add_task(search_service.handle_delete, entity) # pragma: no cover
|
|
356
|
+
|
|
357
|
+
logger.info(f"API v2 response: external_id={entity_id}, deleted={deleted}")
|
|
358
|
+
|
|
359
|
+
return DeleteEntitiesResponse(deleted=deleted)
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
## Move endpoint
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
@router.put("/entities/{entity_id}/move", response_model=EntityResponseV2)
|
|
366
|
+
async def move_entity(
|
|
367
|
+
data: MoveEntityRequestV2,
|
|
368
|
+
background_tasks: BackgroundTasks,
|
|
369
|
+
project_id: ProjectExternalIdPathDep,
|
|
370
|
+
entity_service: EntityServiceV2ExternalDep,
|
|
371
|
+
entity_repository: EntityRepositoryV2ExternalDep,
|
|
372
|
+
project_config: ProjectConfigV2ExternalDep,
|
|
373
|
+
app_config: AppConfigDep,
|
|
374
|
+
search_service: SearchServiceV2ExternalDep,
|
|
375
|
+
entity_id: str = Path(..., description="Entity external ID (UUID)"),
|
|
376
|
+
) -> EntityResponseV2:
|
|
377
|
+
"""Move an entity to a new file location.
|
|
378
|
+
|
|
379
|
+
V2 API uses external_id (UUID) in the URL path for stable references.
|
|
380
|
+
The external_id will remain stable after the move.
|
|
381
|
+
|
|
382
|
+
Args:
|
|
383
|
+
project_id: Project external ID from URL path
|
|
384
|
+
entity_id: Entity external ID from URL path (primary identifier)
|
|
385
|
+
data: Move request with destination path only
|
|
386
|
+
|
|
387
|
+
Returns:
|
|
388
|
+
Updated entity with new file path
|
|
389
|
+
"""
|
|
390
|
+
logger.info(
|
|
391
|
+
f"API v2 request: move_entity entity_id={entity_id}, destination='{data.destination_path}'"
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
try:
|
|
395
|
+
# First, get the entity by external_id to verify it exists
|
|
396
|
+
entity = await entity_repository.get_by_external_id(entity_id)
|
|
397
|
+
if not entity: # pragma: no cover
|
|
398
|
+
raise HTTPException(
|
|
399
|
+
status_code=404, detail=f"Entity with external_id '{entity_id}' not found"
|
|
400
|
+
)
|
|
401
|
+
|
|
402
|
+
# Move the entity using its current file path as identifier
|
|
403
|
+
moved_entity = await entity_service.move_entity(
|
|
404
|
+
identifier=entity.file_path, # Use file path for resolution
|
|
405
|
+
destination_path=data.destination_path,
|
|
406
|
+
project_config=project_config,
|
|
407
|
+
app_config=app_config,
|
|
408
|
+
)
|
|
409
|
+
|
|
410
|
+
# Reindex at new location
|
|
411
|
+
reindexed_entity = await entity_service.link_resolver.resolve_link(data.destination_path)
|
|
412
|
+
if reindexed_entity:
|
|
413
|
+
await search_service.index_entity(reindexed_entity, background_tasks=background_tasks)
|
|
414
|
+
|
|
415
|
+
result = EntityResponseV2.model_validate(moved_entity)
|
|
416
|
+
|
|
417
|
+
logger.info(
|
|
418
|
+
f"API v2 response: moved external_id={entity_id} to '{data.destination_path}'"
|
|
419
|
+
)
|
|
420
|
+
|
|
421
|
+
return result
|
|
422
|
+
|
|
423
|
+
except HTTPException: # pragma: no cover
|
|
424
|
+
raise # pragma: no cover
|
|
425
|
+
except Exception as e:
|
|
426
|
+
logger.error(f"Error moving entity: {e}")
|
|
427
|
+
raise HTTPException(status_code=400, detail=str(e))
|