|
| 1 | +"""Watch command - run file watcher as a standalone long-running process.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import os |
| 5 | +import signal |
| 6 | +import sys |
| 7 | +from typing import Optional |
| 8 | + |
| 9 | +import typer |
| 10 | +from loguru import logger |
| 11 | + |
| 12 | +from basic_memory import db |
| 13 | +from basic_memory.cli.app import app |
| 14 | +from basic_memory.cli.container import get_container |
| 15 | +from basic_memory.config import ConfigManager |
| 16 | +from basic_memory.services.initialization import initialize_app |
| 17 | +from basic_memory.sync.coordinator import SyncCoordinator |
| 18 | + |
| 19 | + |
| 20 | +async def run_watch(project: Optional[str] = None) -> None: |
| 21 | + """Run the file watcher as a long-running process. |
| 22 | +
|
| 23 | + This is the async core of the watch command. It: |
| 24 | + 1. Initializes the app (DB migrations + project reconciliation) |
| 25 | + 2. Validates and sets project constraint if --project given |
| 26 | + 3. Creates a SyncCoordinator with quiet=False for Rich console output |
| 27 | + 4. Blocks until SIGINT/SIGTERM, then shuts down cleanly |
| 28 | + """ |
| 29 | + container = get_container() |
| 30 | + config = container.config |
| 31 | + |
| 32 | + # --- Initialization --- |
| 33 | + # Wrapped in try/finally so DB resources are cleaned up on all exit paths, |
| 34 | + # including early exits from invalid --project names. |
| 35 | + await initialize_app(config) |
| 36 | + sync_coordinator = None |
| 37 | + |
| 38 | + try: |
| 39 | + # --- Project constraint --- |
| 40 | + if project: |
| 41 | + config_manager = ConfigManager() |
| 42 | + project_name, _ = config_manager.get_project(project) |
| 43 | + if not project_name: |
| 44 | + typer.echo(f"No project found named: {project}", err=True) |
| 45 | + raise typer.Exit(1) |
| 46 | + |
| 47 | + os.environ["BASIC_MEMORY_MCP_PROJECT"] = project_name |
| 48 | + logger.info(f"Watch constrained to project: {project_name}") |
| 49 | + |
| 50 | + # --- Sync coordinator --- |
| 51 | + # quiet=False so file change events are printed to the terminal |
| 52 | + sync_coordinator = SyncCoordinator(config=config, should_sync=True, quiet=False) |
| 53 | + |
| 54 | + # --- Signal handling --- |
| 55 | + shutdown_event = asyncio.Event() |
| 56 | + |
| 57 | + def _signal_handler() -> None: |
| 58 | + logger.info("Shutdown signal received") |
| 59 | + shutdown_event.set() |
| 60 | + |
| 61 | + loop = asyncio.get_running_loop() |
| 62 | + |
| 63 | + # Windows ProactorEventLoop does not support add_signal_handler; |
| 64 | + # fall back to the stdlib signal module which works cross-platform. |
| 65 | + try: |
| 66 | + for sig in (signal.SIGINT, signal.SIGTERM): |
| 67 | + loop.add_signal_handler(sig, _signal_handler) |
| 68 | + except NotImplementedError: |
| 69 | + for sig in (signal.SIGINT, signal.SIGTERM): |
| 70 | + signal.signal(sig, lambda _signum, _frame: _signal_handler()) |
| 71 | + |
| 72 | + # --- Run --- |
| 73 | + await sync_coordinator.start() |
| 74 | + logger.info("Watch service running, press Ctrl+C to stop") |
| 75 | + await shutdown_event.wait() |
| 76 | + finally: |
| 77 | + if sync_coordinator is not None: |
| 78 | + await sync_coordinator.stop() |
| 79 | + await db.shutdown_db() |
| 80 | + logger.info("Watch service stopped") |
| 81 | + |
| 82 | + |
| 83 | +@app.command() |
| 84 | +def watch( |
| 85 | + project: Optional[str] = typer.Option(None, help="Restrict watcher to a single project"), |
| 86 | +) -> None: |
| 87 | + """Run file watcher as a long-running process (no MCP server). |
| 88 | +
|
| 89 | + Watches for file changes in project directories and syncs them to the |
| 90 | + database. Useful for running Basic Memory sync alongside external tools |
| 91 | + that don't use the MCP server. |
| 92 | + """ |
| 93 | + # On Windows, use SelectorEventLoop to avoid ProactorEventLoop cleanup issues |
| 94 | + if sys.platform == "win32": # pragma: no cover |
| 95 | + asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) |
| 96 | + |
| 97 | + asyncio.run(run_watch(project=project)) |
0 commit comments