|
| 1 | +"""Orphans command - show entities with no relations in the knowledge graph.""" |
| 2 | + |
| 3 | +import json |
| 4 | +from typing import Annotated, Optional |
| 5 | + |
| 6 | +import typer |
| 7 | +from loguru import logger |
| 8 | +from mcp.server.fastmcp.exceptions import ToolError |
| 9 | +from rich.console import Console |
| 10 | +from rich.table import Table |
| 11 | + |
| 12 | +from basic_memory.cli.app import app |
| 13 | +from basic_memory.cli.commands.routing import force_routing, validate_routing_flags |
| 14 | +from basic_memory.config import ConfigManager |
| 15 | +from basic_memory.mcp.async_client import get_client |
| 16 | +from basic_memory.mcp.clients.knowledge import KnowledgeClient |
| 17 | +from basic_memory.mcp.project_context import get_active_project |
| 18 | + |
| 19 | +console = Console() |
| 20 | + |
| 21 | + |
| 22 | +async def run_orphans(project: Optional[str] = None) -> tuple[str, list[dict]]: |
| 23 | + """Fetch entities that have no relations in the knowledge graph.""" |
| 24 | + project = project or ConfigManager().default_project |
| 25 | + |
| 26 | + async with get_client(project_name=project) as client: |
| 27 | + project_item = await get_active_project(client, project, None) |
| 28 | + entities = await KnowledgeClient(client, project_item.external_id).get_orphans() |
| 29 | + return project_item.name, entities |
| 30 | + |
| 31 | + |
| 32 | +@app.command() |
| 33 | +def orphans( |
| 34 | + project: Annotated[ |
| 35 | + Optional[str], |
| 36 | + typer.Option(help="The project name."), |
| 37 | + ] = None, |
| 38 | + json_output: bool = typer.Option(False, "--json", help="Output in JSON format"), |
| 39 | + local: bool = typer.Option( |
| 40 | + False, "--local", help="Force local API routing (ignore cloud mode)" |
| 41 | + ), |
| 42 | + cloud: bool = typer.Option(False, "--cloud", help="Force cloud API routing"), |
| 43 | +): |
| 44 | + """Show entities that have no relations in the knowledge graph. |
| 45 | +
|
| 46 | + Orphan entities have no incoming or outgoing connections. These may indicate |
| 47 | + newly created notes not yet linked to other entities, or notes that have had |
| 48 | + their relations removed. |
| 49 | + """ |
| 50 | + from basic_memory.cli.commands.command_utils import run_with_cleanup |
| 51 | + |
| 52 | + try: |
| 53 | + validate_routing_flags(local, cloud) |
| 54 | + # Trigger: no explicit routing flag provided. |
| 55 | + # Why: orphans is a project-local graph inspection command like status. |
| 56 | + # Outcome: default to local routing unless --cloud was explicitly requested. |
| 57 | + if not local and not cloud: |
| 58 | + local = True |
| 59 | + with force_routing(local=local, cloud=cloud): |
| 60 | + project_name, entities = run_with_cleanup(run_orphans(project)) |
| 61 | + |
| 62 | + if json_output: |
| 63 | + print(json.dumps(entities, indent=2, default=str)) |
| 64 | + return |
| 65 | + |
| 66 | + if not entities: |
| 67 | + console.print(f"[green]No orphan entities in project '{project_name}'[/green]") |
| 68 | + return |
| 69 | + |
| 70 | + table = Table(title=f"{project_name}: Entities Without Relations ({len(entities)} total)") |
| 71 | + table.add_column("Title", style="cyan") |
| 72 | + table.add_column("File Path", style="yellow") |
| 73 | + table.add_column("Type", style="green") |
| 74 | + |
| 75 | + for entity in entities: |
| 76 | + table.add_row( |
| 77 | + entity.get("title", ""), |
| 78 | + entity.get("file_path", ""), |
| 79 | + entity.get("note_type") or "", |
| 80 | + ) |
| 81 | + |
| 82 | + console.print(table) |
| 83 | + except (ValueError, ToolError) as exc: |
| 84 | + if json_output: |
| 85 | + print(json.dumps({"error": str(exc)}, indent=2)) |
| 86 | + else: |
| 87 | + console.print(f"[red]Error: {exc}[/red]") |
| 88 | + raise typer.Exit(code=1) |
| 89 | + except typer.Exit: |
| 90 | + raise |
| 91 | + except Exception as exc: |
| 92 | + logger.error(f"Error fetching orphan entities: {exc}") |
| 93 | + if json_output: |
| 94 | + print(json.dumps({"error": str(exc)}, indent=2)) |
| 95 | + else: |
| 96 | + console.print(f"[red]Error: {exc}[/red]") |
| 97 | + raise typer.Exit(code=1) # pragma: no cover |
0 commit comments