diff --git a/AGENTS.md b/AGENTS.md index 2702bf018..b82fb9316 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -446,7 +446,7 @@ See `.claude/commands/release/release.md` (and `beta.md`, `release-check.md`, `c - Fetch cloud changes (cloud -> local): `basic-memory cloud pull --name "name"` (Team-safe; additive, never deletes local) - Upload local changes (local -> cloud): `basic-memory cloud push --name "name"` (Team-safe; additive, never deletes cloud) - Resolve conflicts on push/pull: `--on-conflict [fail|keep-local|keep-cloud|keep-both]` (default `fail` lists conflicts and aborts, git-style) -- Deprecated (#1596), Personal workspaces only, to be removed: `basic-memory cloud sync` (one-way mirror; deletes cloud files missing locally), `basic-memory cloud bisync` and `bisync-reset` (two-way mirror). They warn on every run; use pull/push. +- Removed in 1.0 (#1845): `basic-memory cloud sync`, `bisync`, and `bisync-reset`. They exit nonzero with migration guidance and transfer nothing; use pull/push. ### MCP Capabilities @@ -467,7 +467,7 @@ Basic Memory now supports cloud synchronization and storage (requires active sub **File Sync:** - `bm cloud pull` / `bm cloud push`: additive, git-style transfers on Personal and Team workspaces - Conflict resolution with `--on-conflict` -- rclone bisync is deprecated (#1596) +- The rclone mirror commands (`sync`, `bisync`) were removed in 1.0 (#1845) **Cloud Project Management:** - Create and manage projects in the cloud diff --git a/docs/1.0.md b/docs/1.0.md index a980502bd..df41d6ea3 100644 --- a/docs/1.0.md +++ b/docs/1.0.md @@ -8,20 +8,23 @@ neither implies that the current published release includes the change. ## Cloud transfers: replace sync and bisync with push/pull -**Status:** planned for v1.0; implementation tracked in -[#1845](https://github.com/basicmachines-co/basic-memory/issues/1845). +**Status:** implemented on the development branch for 1.0 +([#1845](https://github.com/basicmachines-co/basic-memory/issues/1845)). This completes the deprecation introduced through [#1596](https://github.com/basicmachines-co/basic-memory/issues/1596). -### What is being removed +### What was removed - `bm cloud sync`: destructive one-way mirroring from local files to Cloud. - `bm cloud bisync`: bidirectional mirroring. - `bm cloud bisync-reset`: initialization/reset of bisync state. -The plan is to retain migration-only stubs for these command names in 1.0. They will -exit nonzero with replacement instructions and perform no transfers or deletions. -They will not silently invoke push or pull. +The command names remain as migration-only stubs, hidden from `bm cloud --help`. +Each one prints replacement instructions and exits with status 1. It reads no +credentials, calls no Cloud API, and transfers or deletes nothing. The stubs do not +invoke push or pull. + +`bm project remove` no longer deletes a project's old bisync state directory. ### Why @@ -51,8 +54,8 @@ bm cloud push --name research ``` Use `--workspace ` when the project name is ambiguous. Existing -local path configuration remains useful. `bm cloud sync-setup` is not being removed -by this change: it configures that path, rather than running the legacy mirror. +local path configuration remains useful. `bm cloud sync-setup` is not removed by +this change: it configures that path, rather than running the legacy mirror. Personal transfers still use shared rclone setup; Team transfers use WebDAV with project-level authorization and do not require rclone setup. @@ -118,15 +121,19 @@ bm cloud pull --name research --on-conflict keep-both 5. Handle intentional deletion or rename cleanup separately, after reviewing the affected files. Do not assume a missing local file authorizes Cloud deletion. -The removal must not automatically delete local files, Cloud files, credentials, -or old bisync state directories. Existing backups and snapshots remain independent -of transfer commands. Removing `cloud check` is outside this migration's scope. +The removal does not delete local files, Cloud files, credentials, or old bisync +state directories (`~/.basic-memory/bisync-state/`, or `bisync-state/` under +`BASIC_MEMORY_CONFIG_DIR`). Delete that directory yourself once you no longer need +it. Existing backups and snapshots remain independent of transfer commands. Removing `cloud check` is outside this migration's scope. ### Release checklist -- [ ] Land #1845 and verify the migration-only command errors. +- [ ] Land #1845. The migration-only command errors are covered by + `tests/cli/cloud/test_removed_mirror_commands.py`. - [ ] Verify examples against the 1.0 CLI on Personal and Team workspaces. -- [ ] Update CLI help, manuals, setup output, and public Cloud transfer guides. +- [x] Update CLI help, manuals, setup output, and repository Cloud transfer guides + (`docs/cloud-cli.md`, `bm(1)`, AGENTS.md). +- [ ] Update the public Cloud transfer guides on docs.basicmemory.com. - [ ] Include the removal and behavioral differences in release/upgrade notes. - [ ] Confirm no active documentation recommends sync or bisync as a transfer workflow. diff --git a/docs/cloud-cli.md b/docs/cloud-cli.md index 55c3faf4f..71d00f219 100644 --- a/docs/cloud-cli.md +++ b/docs/cloud-cli.md @@ -22,7 +22,7 @@ The cloud CLI enables you to: `push` and `pull` never delete on the destination, so they are safe on a shared Team bucket. On Personal workspaces they run over rclone; on Team workspaces they run over WebDAV, where the service applies per-project access. You run the same commands either way. -The older rclone mirror commands (`bm cloud sync`, `bm cloud bisync`, `bm cloud bisync-reset`) are **deprecated**. They still run on Personal workspaces, refuse Team workspaces, and will be removed in a future release. See [Deprecated: rclone mirror commands](#deprecated-rclone-mirror-commands-personal-only). +The rclone mirror commands (`bm cloud sync`, `bm cloud bisync`, `bm cloud bisync-reset`) were **removed in 1.0**. See [Removed in 1.0: sync and bisync](#removed-in-10-sync-and-bisync). ## Prerequisites @@ -382,8 +382,9 @@ bm cloud pull --name research --workspace acme `push`/`pull` are deliberately simple, conflict-aware byte transfers — not a full reconciler. Without a sync baseline: -- **Deletions are not propagated.** A note deleted on one side is not removed from the other (we cannot tell an intentional delete from a file the other side never had). This is surfaced in the command output. -- **Every divergence is treated as a conflict.** We cannot tell a teammate's edit from your stale copy, so any differing file prompts a decision rather than auto-resolving. +- **Deletions are not propagated.** A note deleted on one side is not removed from the other (we cannot tell an intentional delete from a file the other side never had). This is surfaced in the command output. A later transfer in the other direction can copy the deleted file back. +- **Renames are not propagated as moves.** The file at its new path transfers, and the old path remains on the destination until you remove it. +- **Every divergence is treated as a conflict.** We cannot tell a teammate's edit from your stale copy, so any differing file prompts a decision rather than auto-resolving. There is no automatic three-way merge. For conflict-aware *editing*, write through the MCP/API tools (which merge at the note level). A bidirectional reconciler with a real baseline is tracked in [issue #862](https://github.com/basicmachines-co/basic-memory/issues/862). @@ -763,48 +764,26 @@ bm cloud status If instance is down, wait a few minutes and retry. -## Deprecated: rclone mirror commands (Personal only) +## Removed in 1.0: sync and bisync -`bm cloud sync`, `bm cloud bisync`, and `bm cloud bisync-reset` are **deprecated and will be removed in a future release**. Use `bm cloud pull` / `bm cloud push` instead. +`bm cloud sync`, `bm cloud bisync`, and `bm cloud bisync-reset` were removed in 1.0 ([#1845](https://github.com/basicmachines-co/basic-memory/issues/1845)). `sync` made the cloud match your local folder and deleted cloud-only files, including notes created in the cloud by teammates and agents. Running any of the three now prints migration guidance and exits nonzero. It transfers, deletes, and provisions nothing. -Until removal: -- They are marked deprecated in `--help`. -- Every run prints a deprecation warning that points to `bm cloud pull --name ` / `bm cloud push --name `. -- They still run on Personal workspaces. -- They refuse Team workspaces. As mirrors, they can delete a teammate's files on a shared bucket. +Replace them with `bm cloud pull` and `bm cloud push`: -`bm cloud check` is a legacy, Personal-only command that compares against the same mirror remote. Use `bm cloud pull --dry-run` / `bm cloud push --dry-run` to preview differences instead. - -This section is kept so existing users can keep working until the commands are removed. - -### sync (deprecated): one-way mirror, local → cloud - -```bash -bm cloud sync --name research --dry-run -bm cloud sync --name research -``` - -Makes the cloud identical to local with `rclone sync`. Cloud files that are missing locally are **deleted**. Preview deletions with `--dry-run`. - -### bisync (deprecated): two-way mirror, local ↔ cloud - -```bash -# First run: establish a baseline -bm cloud bisync --name research --resync --dry-run -bm cloud bisync --name research --resync - -# Later runs -bm cloud bisync --name research -``` +| Old command | Replacement | +|---|---| +| `bm cloud sync --name research` | `bm cloud push --name research` (add `--on-conflict keep-local` for local precedence) | +| `bm cloud bisync --name research` | `bm cloud pull --name research`, then `bm cloud push --name research` | +| `bm cloud bisync-reset research` | Nothing to reset: push and pull keep no sync state | -Syncs both directions and can delete or overwrite on both sides. Conflicts resolve as newer file wins. State lives in `~/.basic-memory/bisync-state//`. +How the replacements differ from mirroring: -- **"First bisync requires --resync"** - Run once with `--resync` to create the baseline. Do not use `--resync` again unless you need a new baseline. -- **"Empty prior Path1 listing. Cannot sync to an empty directory"** - Bisync cannot baseline an empty directory. Add a file (for example a `README.md`) and run `--resync` again. -- **"max delete limit (25) exceeded"** - Bisync stops when a run would delete more than 25 files. Check with `--dry-run`, then run `--resync` if the deletes are intended. -- **Corrupted state or listing files** - Clear the state with `bm cloud bisync-reset research`, then run `--resync`. This does not touch your files. Removing a project also clears its bisync state. +- **Deletions are not propagated.** Delete the cloud copy yourself if you deleted a file locally, and the reverse. +- **Renames are not propagated as moves.** The old path remains on the destination until you remove it. +- **Any differing file is a conflict.** The transfer stops before copying anything. Re-run with `--on-conflict keep-local`, `keep-cloud`, or `keep-both`. +- **`push --on-conflict keep-local` is not an exact mirror.** Local content wins for differing files, but cloud-only files remain. -To move off bisync, run `bm cloud pull --name ` and `bm cloud push --name ` instead. They need no baseline or state. +Old bisync state in `~/.basic-memory/bisync-state/` is no longer used. Basic Memory does not delete it; remove it yourself if you like. To clean up cloud files that match `.bmignore`, use `bm cloud prune --name --dry-run` on Personal workspaces. ### check (legacy): verify mirror integrity @@ -813,7 +792,7 @@ bm cloud check --name research bm cloud check --name research --one-way # faster, one direction ``` -Compares checksums between local and the Personal mirror remote. No files are transferred. +Compares checksums between local and the default Personal workspace remote. No files are transferred. Use `bm cloud pull --dry-run` / `bm cloud push --dry-run` to preview differences instead. ## Security @@ -890,13 +869,11 @@ bm project ls --name --cloud bm project ls --name --cloud --path ``` -### Deprecated (Personal only, removed in a future release) +### Legacy (Personal only) ```bash -bm cloud sync --name # Deprecated one-way mirror -bm cloud bisync --name [--resync] # Deprecated two-way mirror -bm cloud bisync-reset # Deprecated: clear bisync state -bm cloud check --name # Legacy mirror integrity check +bm cloud check --name # Legacy integrity check +bm cloud prune --name [--dry-run] # Delete cloud files matching .bmignore ``` ## Summary diff --git a/integrations/hermes/README.md b/integrations/hermes/README.md index a62052af1..d12dce89c 100644 --- a/integrations/hermes/README.md +++ b/integrations/hermes/README.md @@ -192,7 +192,7 @@ hermes gateway restart Tool calls now route from `bm mcp` → `/proxy` over HTTPS using your OAuth token (or API key). Notes never touch local disk. -**Don't confuse cloud mode with file sync.** `bm cloud pull` / `bm cloud push` copy files between a *local* project and cloud storage, for keeping local working copies (`bm cloud bisync` is deprecated). For agent-driven capture you want true cloud routing (`set-cloud`), not file sync. +**Don't confuse cloud mode with file sync.** `bm cloud pull` / `bm cloud push` copy files between a *local* project and cloud storage, for keeping local working copies. For agent-driven capture you want true cloud routing (`set-cloud`), not file sync. ## Updating / removing diff --git a/src/basic_memory/cli/commands/cloud/__init__.py b/src/basic_memory/cli/commands/cloud/__init__.py index 35a1d974d..69cbbc7b3 100644 --- a/src/basic_memory/cli/commands/cloud/__init__.py +++ b/src/basic_memory/cli/commands/cloud/__init__.py @@ -7,6 +7,7 @@ from basic_memory.cli.commands.cloud.api_client import get_authenticated_headers, get_cloud_config # noqa: F401 from basic_memory.cli.commands.cloud.upload_command import * # noqa: F401,F403 from basic_memory.cli.commands.cloud.project_sync import * # noqa: F401,F403 +from basic_memory.cli.commands.cloud.removed_mirror_commands import * # noqa: F401,F403 # Register snapshot sub-command group from basic_memory.cli.commands.cloud.snapshot import snapshot_app diff --git a/src/basic_memory/cli/commands/cloud/core_commands.py b/src/basic_memory/cli/commands/cloud/core_commands.py index 15154e921..89a44eedd 100644 --- a/src/basic_memory/cli/commands/cloud/core_commands.py +++ b/src/basic_memory/cli/commands/cloud/core_commands.py @@ -21,8 +21,8 @@ get_cloud_config, make_api_request, ) -from basic_memory.cli.commands.cloud.bisync_commands import ( - BisyncError, +from basic_memory.cli.commands.cloud.mount_api import ( + MountApiError, generate_mount_credentials, get_mount_info, ) @@ -295,7 +295,7 @@ def setup( "\n[dim]Tip: Always use --dry-run first to preview changes before syncing[/dim]" ) - except (RcloneInstallError, BisyncError, CloudAPIError) as e: + except (RcloneInstallError, MountApiError, CloudAPIError) as e: console.print(f"\n[red]Setup failed: {literal(e)}[/red]") raise typer.Exit(1) except typer.Exit: diff --git a/src/basic_memory/cli/commands/cloud/mount_api.py b/src/basic_memory/cli/commands/cloud/mount_api.py new file mode 100644 index 000000000..bc3bf167d --- /dev/null +++ b/src/basic_memory/cli/commands/cloud/mount_api.py @@ -0,0 +1,74 @@ +"""Cloud mount API calls for Personal rclone transfers. + +`bm cloud setup` mints bucket-scoped storage credentials through these calls, +and the Personal `push`/`pull`/`prune`/`check` commands read the tenant's +bucket name from the mount info endpoint. +""" + +from basic_memory.cli.commands.cloud.api_client import make_api_request +from basic_memory.config import ConfigManager +from basic_memory.schemas.cloud import MountCredentials, TenantMountInfo + + +class MountApiError(Exception): + """Exception raised when a cloud mount API call fails.""" + + pass + + +def _workspace_id_header(workspace_id: str | None) -> dict[str, str]: + """Header that routes a /tenant/mount/* request to a specific tenant. + + The mount endpoints resolve the workspace from X-Workspace-ID (validating + membership + subscription) and fall back to the user's default tenant when + it is absent — so omitting it preserves the original default-tenant behavior. + """ + return {"X-Workspace-ID": workspace_id} if workspace_id else {} + + +async def get_mount_info(*, workspace_id: str | None = None) -> TenantMountInfo: + """Get tenant mount info (bucket name + tenant id) from the cloud API. + + Args: + workspace_id: Tenant id of the target workspace. When omitted, the API + uses the authenticated user's default tenant. + """ + try: + config_manager = ConfigManager() + config = config_manager.config + host_url = config.cloud_host.rstrip("/") + + response = await make_api_request( + method="GET", + url=f"{host_url}/tenant/mount/info", + headers=_workspace_id_header(workspace_id), + ) + + return TenantMountInfo.model_validate(response.json()) + except Exception as e: + raise MountApiError(f"Failed to get tenant info: {e}") from e + + +async def generate_mount_credentials(tenant_id: str) -> MountCredentials: + """Generate scoped S3 credentials for transfers against a tenant's bucket. + + Args: + tenant_id: Tenant id whose bucket-scoped credentials to mint. Routed via + X-Workspace-ID so team workspaces get their own bucket's credentials. + """ + try: + config_manager = ConfigManager() + config = config_manager.config + host_url = config.cloud_host.rstrip("/") + + # The mount endpoints resolve X-Workspace-ID by matching the workspace's + # tenant_id, so passing a tenant_id here is the correct routing key. + response = await make_api_request( + method="POST", + url=f"{host_url}/tenant/mount/credentials", + headers=_workspace_id_header(tenant_id), + ) + + return MountCredentials.model_validate(response.json()) + except Exception as e: + raise MountApiError(f"Failed to generate credentials: {e}") from e diff --git a/src/basic_memory/cli/commands/cloud/project_sync.py b/src/basic_memory/cli/commands/cloud/project_sync.py index 3c41e8893..2b1e4cf7e 100644 --- a/src/basic_memory/cli/commands/cloud/project_sync.py +++ b/src/basic_memory/cli/commands/cloud/project_sync.py @@ -1,10 +1,9 @@ -"""Cloud sync commands for Basic Memory projects. +"""Cloud transfer commands for Basic Memory projects. -`bm cloud pull` / `bm cloud push` are the supported way to move files between a -local project and Basic Memory Cloud, on Personal and Team workspaces alike. The -rclone mirror commands (`sync`, `bisync`, `bisync-reset`) are deprecated (#1596): -they still run on Personal workspaces, warn on every run, and refuse Team -workspaces with the push/pull command to use instead. +`bm cloud pull` / `bm cloud push` are the way to move files between a local +project and Basic Memory Cloud, on Personal and Team workspaces alike. The +rclone mirror commands (`sync`, `bisync`, `bisync-reset`) were removed in 1.0 +(#1845); `removed_mirror_commands` keeps their names as migration stubs. """ import os @@ -12,25 +11,20 @@ from datetime import datetime from enum import Enum from pathlib import Path -from typing import TYPE_CHECKING, override import typer from rich.console import Console -from typer.core import TyperCommand from basic_memory.cli.app import cloud_app -from basic_memory.cli.commands.cloud.bisync_commands import get_mount_info +from basic_memory.cli.commands.cloud.mount_api import get_mount_info from basic_memory.cli.commands.cloud.rclone_commands import ( RcloneError, SyncProject, get_bmignore_prune_filter_path, - get_project_bisync_state, - project_bisync, project_check, project_diff, project_prune, project_prune_preview, - project_sync, project_transfer, ) from basic_memory.ignore_utils import get_bmignore_path @@ -62,31 +56,8 @@ from basic_memory.utils import generate_permalink, normalize_project_path from basic_memory.cli.markup import literal -if TYPE_CHECKING: - # Typer 0.26 vendors Click as `typer._click`; older Typer releases allowed by - # our `typer>=0.9.0` pin do not have that module, so never import it at runtime. - from typer._click.core import Context - console = Console() -MIRROR_DEPRECATION_NOTICE = ( - "`bm cloud {command}` is deprecated and will be removed in a future release.\n" - "Use `bm cloud pull --name {name}` (fetch) / `bm cloud push --name {name}` " - "(additive upload) instead. They work on Personal and Team workspaces." -) - -TEAM_WORKSPACE_BISYNC_UNSUPPORTED = ( - "`bm cloud bisync` is deprecated and does not run on Team workspaces.\n" - "Use `bm cloud pull --name {name}` / `bm cloud push --name {name}` instead." -) - -TEAM_WORKSPACE_SYNC_UNSUPPORTED = ( - "`bm cloud sync` is deprecated and does not run on Team workspaces: it mirrors " - "local onto the shared bucket and can delete a teammate's files.\n" - "Use `bm cloud pull --name {name}` (fetch) / `bm cloud push --name {name}` " - "(additive upload) instead." -) - TEAM_WORKSPACE_PRUNE_UNSUPPORTED = ( "The prune operation deletes files from the shared bucket based on your " "local .bmignore, which could remove a teammate's files, so it is only " @@ -114,34 +85,9 @@ class ConflictStrategy(str, Enum): keep_both = "keep-both" -class MirrorCommand(TyperCommand): - """A deprecated mirror command that prints only our own deprecation notice. - - Click prints "DeprecationWarning: The command 'sync' is deprecated." before - any command whose ``deprecated`` flag is set, and Typer reads the same flag - to mark the command ``(deprecated)`` in help. The mirror commands keep the - flag for the help marker and print MIRROR_DEPRECATION_NOTICE themselves, - which names the pull/push commands to run, so this skips Click's line. - """ - - @override - def invoke(self, ctx: "Context") -> object: - # Typer builds every command from a decorated function. - assert self.callback is not None - return ctx.invoke(self.callback, **ctx.params) - - # --- Shared helpers --- -def _warn_mirror_deprecated(command: str, name: str) -> None: - """Print the deprecation notice every deprecated mirror command shows on each run.""" - notice = MIRROR_DEPRECATION_NOTICE.format(command=command, name=shlex.quote(name)) - # markup=False: the project name is user text, and a name like `[bold]x[/bold]` - # would otherwise render as `x`, so the copied pull/push command would be wrong. - console.print(notice, style="yellow", markup=False) - - def _has_cloud_credentials(config: BasicMemoryConfig) -> bool: """Return whether cloud credentials are available (API key or OAuth token).""" from basic_memory.config import has_cloud_credentials @@ -221,17 +167,11 @@ async def _get_workspace_for_project( ) -def _require_personal_workspace( - name: str, - config: BasicMemoryConfig, - *, - unsupported_message: str = TEAM_WORKSPACE_BISYNC_UNSUPPORTED, -) -> WorkspaceInfo: - """Exit before mirror work when the target workspace is not personal. +def _require_personal_workspace(name: str, config: BasicMemoryConfig) -> WorkspaceInfo: + """Exit before prune work when the target workspace is not personal. - Used to gate the destructive mirror operations (`sync`, `bisync`) to - Personal workspaces. ``unsupported_message`` lets each command point Team - users at the right Team-safe alternative. + Prune deletes from the bucket based on this machine's .bmignore, so it is + gated to Personal workspaces; Team users are pointed at push/pull. """ try: workspace = run_with_cleanup(_get_workspace_for_project(name, config)) @@ -242,9 +182,13 @@ def _require_personal_workspace( raise typer.Exit(1) if workspace.workspace_type != "personal": - # The templates below embed `--name {name}`; quote it before rendering so a - # name with a space stays one argument in the command they print. - console.print(unsupported_message.format(name=shlex.quote(name)), style="red", markup=False) + # The template embeds `--name {name}`; quote it before rendering so a + # name with a space stays one argument in the command it prints. + console.print( + TEAM_WORKSPACE_PRUNE_UNSUPPORTED.format(name=shlex.quote(name)), + style="red", + markup=False, + ) raise typer.Exit(1) return workspace @@ -317,76 +261,6 @@ def _get_sync_project( # --- Commands --- -@cloud_app.command("sync", deprecated=True, cls=MirrorCommand) -def sync_project_command( - name: str = typer.Option(..., "--name", "--project", help="Project name to sync"), - dry_run: bool = typer.Option(False, "--dry-run", help="Preview changes without syncing"), - verbose: bool = typer.Option(False, "--verbose", "-v", help="Show detailed output"), -) -> None: - """One-way mirror: local -> cloud (make cloud identical to local). - - Use `bm cloud push` / `bm cloud pull` instead. Personal workspaces only. This deletes cloud files not present locally — - including files matching .bmignore, even if they synced before the pattern - was added — so on Team workspaces use `bm cloud push` (additive upload) / - `bm cloud pull` (fetch) instead. Preview deletions with --dry-run. - - Example: - bm cloud sync --name research - bm cloud sync --name research --dry-run - """ - config = ConfigManager().config - # The migration notice comes first so a missing login still shows pull/push. - _warn_mirror_deprecated("sync", name) - _require_cloud_credentials(config) - target_workspace = _require_personal_workspace( - name, - config, - unsupported_message=TEAM_WORKSPACE_SYNC_UNSUPPORTED, - ) - - try: - remote_name = remote_name_for_workspace( - target_workspace.slug, - is_default=target_workspace.is_default, - ) - tenant_info = run_with_cleanup(get_mount_info(workspace_id=target_workspace.tenant_id)) - bucket_name = tenant_info.bucket_name - - # Resolve project metadata, bucket credentials, and rclone remote from - # the same Personal workspace. A same-named project may exist elsewhere. - with force_routing(cloud=True): - project_data = run_with_cleanup( - _get_cloud_project(name, workspace_id=target_workspace.tenant_id) - ) - if not project_data: - console.print(f"[red]Error: Project '{literal(name)}' not found[/red]") - raise typer.Exit(1) - - sync_project, local_sync_path = _get_sync_project( - name, - config, - project_data, - remote_name=remote_name, - ) - - # Run sync - console.print(f"[blue]Syncing {literal(name)} (local -> cloud)...[/blue]") - success = project_sync(sync_project, bucket_name, dry_run=dry_run, verbose=verbose) - - if success: - console.print(f"[green]{literal(name)} synced successfully[/green]") - else: - console.print(f"[red]{literal(name)} sync failed[/red]") - raise typer.Exit(1) - - except RcloneError as e: - console.print(f"[red]Sync error: {literal(e)}[/red]") - raise typer.Exit(1) - except Exception as e: - console.print(f"[red]Error: {literal(e)}[/red]") - raise typer.Exit(1) - - @cloud_app.command("prune") def prune_project_command( name: str = typer.Option(..., "--name", "--project", help="Project name to prune"), @@ -400,8 +274,8 @@ def prune_project_command( Targeted cleanup for files that synced before their pattern was added to .bmignore in the Basic Memory config directory ($BASIC_MEMORY_CONFIG_DIR, - default ~/.basic-memory). The sync filter hides ignored paths from normal - deletion, stranding them on the cloud (#1032). Prune lists the + default ~/.basic-memory). Push and pull skip ignored paths and never + delete, so those uploads stay on the cloud (#1032). Prune lists the matching remote files and deletes them only after confirmation. Personal workspaces only: prune deletes from the bucket based on this @@ -415,11 +289,7 @@ def prune_project_command( """ config = ConfigManager().config _require_cloud_credentials(config) - target_workspace = _require_personal_workspace( - name, - config, - unsupported_message=TEAM_WORKSPACE_PRUNE_UNSUPPORTED, - ) + target_workspace = _require_personal_workspace(name, config) try: remote_name = remote_name_for_workspace( @@ -440,7 +310,7 @@ def prune_project_command( console.print(f"[red]Error: Project '{literal(name)}' not found[/red]") raise typer.Exit(1) - # Prune inspects and deletes only remote files, so unlike sync/bisync it + # Prune inspects and deletes only remote files, so unlike push/pull it # needs no local_sync_path — cleanup works from any machine that has the # .bmignore patterns. sync_project = SyncProject( @@ -833,78 +703,6 @@ def push_project_command( ) -@cloud_app.command("bisync", deprecated=True, cls=MirrorCommand) -def bisync_project_command( - name: str = typer.Option(..., "--name", "--project", help="Project name to bisync"), - dry_run: bool = typer.Option(False, "--dry-run", help="Preview changes without syncing"), - resync: bool = typer.Option(False, "--resync", help="Force new baseline"), - verbose: bool = typer.Option(False, "--verbose", "-v", help="Show detailed output"), -) -> None: - """Two-way mirror: local <-> cloud (bidirectional sync). - - Use `bm cloud pull` (fetch) / `bm cloud push` (additive upload) instead. - Personal workspaces only: this mirror can delete and overwrite files on - both sides. - - Examples: - bm cloud bisync --name research --resync # First time - bm cloud bisync --name research # Subsequent syncs - bm cloud bisync --name research --dry-run # Preview changes - """ - config = ConfigManager().config - # The migration notice comes first so a missing login still shows pull/push. - _warn_mirror_deprecated("bisync", name) - _require_cloud_credentials(config) - _require_personal_workspace(name, config) - - try: - # Get tenant info for bucket name. - # TODO(#919): scope to the project's workspace like push/pull. Safe for now - # because these mirror commands are gated to the (default-tenant) Personal - # workspace, so the default mount info is correct. - tenant_info = run_with_cleanup(get_mount_info()) - bucket_name = tenant_info.bucket_name - - # Get project info - with force_routing(cloud=True): - project_data = run_with_cleanup(_get_cloud_project(name)) - if not project_data: - console.print(f"[red]Error: Project '{literal(name)}' not found[/red]") - raise typer.Exit(1) - - sync_project, local_sync_path = _get_sync_project(name, config, project_data) - - # Run bisync - console.print(f"[blue]Bisync {literal(name)} (local <-> cloud)...[/blue]") - success = project_bisync( - sync_project, bucket_name, dry_run=dry_run, resync=resync, verbose=verbose - ) - - if success: - console.print(f"[green]{literal(name)} bisync completed successfully[/green]") - - # Update config — sync_entry is guaranteed non-None because - # _get_sync_project validated local_sync_path (which comes from sync_entry) - sync_entry = config.projects.get(name) - if sync_entry is None: - raise RuntimeError( - f"Sync entry for project '{name}' unexpectedly missing after validation" - ) - sync_entry.last_sync = datetime.now() - sync_entry.bisync_initialized = True - ConfigManager().save_config(config) - else: - console.print(f"[red]{literal(name)} bisync failed[/red]") - raise typer.Exit(1) - - except RcloneError as e: - console.print(f"[red]Bisync error: {literal(e)}[/red]") - raise typer.Exit(1) - except Exception as e: - console.print(f"[red]Error: {literal(e)}[/red]") - raise typer.Exit(1) - - @cloud_app.command("check") def check_project_command( name: str = typer.Option(..., "--name", "--project", help="Project name to check"), @@ -912,10 +710,9 @@ def check_project_command( ) -> None: """Verify file integrity between local and cloud (no changes made). - Legacy, Personal workspaces only: check compares against the Personal - workspace mirror remote used by the deprecated `sync` / `bisync` commands. - Use `bm cloud pull --dry-run` / `bm cloud push --dry-run` to preview - differences instead. + Legacy, Personal workspaces only: check compares against the default + Personal workspace remote. Use `bm cloud pull --dry-run` / + `bm cloud push --dry-run` to preview differences instead. Example: bm cloud check --name research @@ -925,9 +722,8 @@ def check_project_command( try: # Get tenant info for bucket name. - # TODO(#919): scope to the project's workspace like push/pull. Safe for now - # because these mirror commands are gated to the (default-tenant) Personal - # workspace, so the default mount info is correct. + # TODO(#919): scope to the project's workspace like push/pull. Check + # reads the default tenant's mount info and remote. tenant_info = run_with_cleanup(get_mount_info()) bucket_name = tenant_info.bucket_name @@ -957,49 +753,6 @@ def check_project_command( raise typer.Exit(1) -@cloud_app.command("bisync-reset", deprecated=True, cls=MirrorCommand) -def bisync_reset( - name: str = typer.Argument(..., help="Project name to reset bisync state for"), -) -> None: - """Clear bisync state for a project. - - `bm cloud bisync` is deprecated; use `bm cloud pull` / `bm cloud push` - instead. Personal workspaces only. - - This removes the bisync metadata files, forcing a fresh --resync on next bisync. - Useful when bisync gets into an inconsistent state or when remote path changes. - """ - import shutil - - config = ConfigManager().config - _warn_mirror_deprecated("bisync-reset", name) - if _has_cloud_credentials(config): - _require_personal_workspace(name, config) - - try: - state_path = get_project_bisync_state(name) - - if not state_path.exists(): - console.print(f"[yellow]No bisync state found for project '{literal(name)}'[/yellow]") - return - - # Remove the entire state directory - shutil.rmtree(state_path) - console.print(f"[green]Cleared bisync state for project '{literal(name)}'[/green]") - console.print("\nNext steps:") - console.print( - f" 1. Preview: " - f"{literal(shell_command('bm', 'cloud', 'bisync', '--name', name, '--resync', '--dry-run'))}" - ) - console.print( - f" 2. Sync: {literal(shell_command('bm', 'cloud', 'bisync', '--name', name, '--resync'))}" - ) - - except Exception as e: - console.print(f"[red]Error clearing bisync state: {literal(str(e))}[/red]") - raise typer.Exit(1) - - @cloud_app.command("sync-setup") def setup_project_sync( name: str = typer.Argument(..., help="Project name"), @@ -1063,8 +816,7 @@ async def _create_local_project(): console.print(f"[green]Sync configured for project '{literal(name)}'[/green]") console.print(f"\nLocal sync path: {literal(resolved_path)}") - # Push/pull is the supported sync workflow on every workspace; the - # `sync`/`bisync` mirrors are deprecated (#1596), so they are not suggested. + # Push/pull is the transfer workflow on every workspace. console.print("\nNext steps:") console.print( f" 1. Preview a pull: {literal(shell_command('bm', 'cloud', 'pull', '--name', name, '--dry-run'))}" diff --git a/src/basic_memory/cli/commands/cloud/rclone_commands.py b/src/basic_memory/cli/commands/cloud/rclone_commands.py index 67356c2b4..58f884581 100644 --- a/src/basic_memory/cli/commands/cloud/rclone_commands.py +++ b/src/basic_memory/cli/commands/cloud/rclone_commands.py @@ -1,26 +1,27 @@ -"""Project-scoped rclone sync commands for Basic Memory Cloud. +"""Project-scoped rclone operations for Personal Basic Memory Cloud workspaces. -This module provides simplified, project-scoped rclone operations: -- Each project syncs independently +This module provides the rclone half of the Personal cloud commands: +- `push` / `pull` (additive `rclone check` + `rclone copy`; never delete) +- `prune` (confirmed deletion of cloud files matching .bmignore) +- `check` and `project ls` - Routes through the project's tenant-scoped remote (SyncProject.remote_name); the default tenant keeps "basic-memory-cloud", others use their own (see #919) -- Balanced defaults from SPEC-8 Phase 4 testing -- Per-project bisync state tracking (for the deprecated `bm cloud bisync`, #1596) -Replaces tenant-wide sync with project-scoped workflows. +The rclone mirror commands (`sync`, `bisync`) were removed in 1.0 (#1845). """ -import re import subprocess from collections.abc import Sequence from dataclasses import dataclass -from functools import lru_cache from pathlib import Path from typing import Callable, Optional, Protocol -from loguru import logger from rich.console import Console +from basic_memory.cli.commands.cloud.rclone_filters import ( + convert_bmignore_to_rclone_filters, + convert_bmignore_to_rclone_prune_filters, +) from basic_memory.cli.commands.cloud.rclone_installer import is_rclone_installed from basic_memory.cli.commands.cloud.transfer import ( ConflictStrategy, @@ -29,19 +30,15 @@ conflict_copy_name, strategy_overwrites_dest, ) -from basic_memory.utils import shell_command -from basic_memory.config import resolve_data_dir from basic_memory.utils import normalize_project_path console = Console() -# Minimum rclone version for --create-empty-src-dirs support -MIN_RCLONE_VERSION_EMPTY_DIRS = (1, 64, 0) - # Tigris edge caching returns stale data for users outside the origin region (iad). # --header is rclone's global flag that applies to ALL HTTP transactions (list, download, -# upload). This is critical because bisync starts with S3 ListObjectsV2, which is neither -# a download nor upload — so --header-download/--header-upload would miss list requests. +# upload). This is critical because `rclone check` and `rclone lsf` start with S3 +# ListObjectsV2, which is neither a download nor upload — so +# --header-download/--header-upload would miss list requests. # See: https://www.tigrisdata.com/docs/objects/consistency/ TIGRIS_CONSISTENCY_HEADERS = [ "--header", @@ -85,41 +82,6 @@ def check_rclone_installed(is_installed: IsInstalledFunc = is_rclone_installed) ) -@lru_cache(maxsize=1) -def get_rclone_version(run: RunFunc = subprocess.run) -> tuple[int, int, int] | None: - """Get rclone version as (major, minor, patch) tuple. - - Returns: - Version tuple like (1, 64, 2), or None if version cannot be determined. - - Note: - Result is cached since rclone version won't change during runtime. - """ - try: - result = run(["rclone", "version"], capture_output=True, text=True, timeout=10) - # Parse "rclone v1.64.2" or "rclone v1.60.1-DEV" - match = re.search(r"v(\d+)\.(\d+)\.(\d+)", result.stdout) - if match: - version = (int(match.group(1)), int(match.group(2)), int(match.group(3))) - logger.debug(f"Detected rclone version: {version}") - return version - except Exception as e: - logger.warning(f"Could not determine rclone version: {e}") - return None - - -def supports_create_empty_src_dirs(version: tuple[int, int, int] | None) -> bool: - """Check if installed rclone supports --create-empty-src-dirs flag. - - Returns: - True if rclone version >= 1.64.0, False otherwise. - """ - if version is None: - # If we can't determine version, assume older and skip the flag - return False - return version >= MIN_RCLONE_VERSION_EMPTY_DIRS - - @dataclass class SyncProject: """Project configured for cloud sync. @@ -139,11 +101,7 @@ class SyncProject: remote_name: str = "basic-memory-cloud" -def get_bmignore_filter_path( - *, - force: bool = False, - fail_on_read_error: bool = False, -) -> Path: +def get_bmignore_filter_path() -> Path: """Get path to rclone filter file. Uses /.bmignore converted to rclone format. @@ -152,15 +110,7 @@ def get_bmignore_filter_path( Returns: Path to rclone filter file """ - # Import here to avoid circular dependency - from basic_memory.cli.commands.cloud.bisync_commands import ( - convert_bmignore_to_rclone_filters, - ) - - return convert_bmignore_to_rclone_filters( - force=force, - fail_on_read_error=fail_on_read_error, - ) + return convert_bmignore_to_rclone_filters() def get_bmignore_prune_filter_path() -> Path: @@ -172,42 +122,9 @@ def get_bmignore_prune_filter_path() -> Path: Returns: Path to inverted rclone filter file """ - # Import here to avoid circular dependency - from basic_memory.cli.commands.cloud.bisync_commands import ( - convert_bmignore_to_rclone_prune_filters, - ) - return convert_bmignore_to_rclone_prune_filters() -def get_project_bisync_state(project_name: str) -> Path: - """Get path to project's bisync state directory. - - Honors ``BASIC_MEMORY_CONFIG_DIR`` so isolated instances each keep their - own bisync state alongside their config. - - Args: - project_name: Name of the project - - Returns: - Path to bisync state directory for this project - """ - return resolve_data_dir() / "bisync-state" / project_name - - -def bisync_initialized(project_name: str) -> bool: - """Check if bisync has been initialized for this project. - - Args: - project_name: Name of the project - - Returns: - True if bisync state exists, False otherwise - """ - state_path = get_project_bisync_state(project_name) - return state_path.exists() and any(state_path.iterdir()) - - def get_project_remote(project: SyncProject, bucket_name: str) -> str: """Build rclone remote path for project. @@ -234,8 +151,8 @@ def get_project_remote(project: SyncProject, bucket_name: str) -> str: # --- Directional transfer primitives (push / pull) --- # # These power the `bm cloud push` / `bm cloud pull` commands on Personal -# workspaces. Unlike the mirror operations (`sync`/`bisync`), they use -# `rclone copy` so they never delete on the destination, and conflicts are +# workspaces. Unlike the removed mirror commands (`sync`/`bisync`, #1845), they +# use `rclone copy` so they never delete on the destination, and conflicts are # surfaced to the caller rather than silently resolved. See issue #858 for the # full design rationale. Team workspaces run the same commands over the WebDAV # transport instead (`webdav_transfer.py`, #1262); the plan vocabulary both @@ -296,71 +213,6 @@ def _build_transfer_cmd( return cmd -def project_sync( - project: SyncProject, - bucket_name: str, - dry_run: bool = False, - verbose: bool = False, - *, - run: RunFunc = subprocess.run, - is_installed: IsInstalledFunc = is_rclone_installed, - filter_path: Path | None = None, -) -> bool: - """One-way sync: local → cloud. - - Makes cloud identical to local using rclone sync. Cloud files matching the - .bmignore filter are deleted too (--delete-excluded), so a file added to - .bmignore after it synced does not linger on the remote (#1032). - - Args: - project: Project to sync - bucket_name: S3 bucket name - dry_run: Preview changes without applying - verbose: Show detailed output - - Returns: - True if sync succeeded, False otherwise - - Raises: - RcloneError: If project has no local_sync_path configured or rclone not installed - """ - check_rclone_installed(is_installed=is_installed) - - if not project.local_sync_path: - raise RcloneError(f"Project {project.name} has no local_sync_path configured") - - local_path = Path(project.local_sync_path).expanduser() - remote_path = get_project_remote(project, bucket_name) - # --delete-excluded makes this filter destructive. Rebuild it from the - # current .bmignore even when filesystem mtimes make the cache look newer. - filter_path = filter_path or get_bmignore_filter_path( - force=True, - fail_on_read_error=True, - ) - - cmd = _build_transfer_cmd( - "sync", - str(local_path), - remote_path, - filter_path=filter_path, - dry_run=dry_run, - verbose=verbose, - # Trigger: a file synced to cloud, then its pattern was added to .bmignore. - # Why: the filter hides ignored paths on both sides of the transfer, so - # without this flag the remote copy is stranded — invisible to rclone's - # deletion pass yet still stored and indexed on the tenant (#1032). That - # breaks this mirror's "make cloud identical to local" contract, since - # the filtered local set no longer contains the file. - # Outcome: rclone deletes destination files excluded by the filter. - # Scoped to this one-way personal mirror only — never bisync/push/pull, - # which must not delete based on a single machine's local ignore file. - extra_flags=("--delete-excluded",), - ) - - result = run(cmd, text=True) - return result.returncode == 0 - - def _parse_check_combined(output: str) -> TransferPlan: """Parse ``rclone check --combined`` output into a TransferPlan. @@ -597,7 +449,7 @@ def project_transfer( # --- Prune (issue #1032) --- # -# The sync/bisync filter hides .bmignore paths on both sides of a transfer, so +# The transfer filter hides .bmignore paths on both sides of a transfer, so # a file uploaded before its pattern was added to .bmignore is stranded on the # cloud tenant. Prune targets exactly that set: it uses the *inverted* filter # (each ignore pattern becomes an include rule, everything else is excluded) so @@ -665,9 +517,8 @@ def project_prune( ) -> bool: """Delete exactly the remote files returned by the confirmed preview. - Complements the one-way mirror's --delete-excluded pass (#1032): targeted - cleanup for files uploaded before their pattern was added to .bmignore, - without requiring a full mirror run or a configured local_sync_path. + Targeted cleanup for files uploaded before their pattern was added to + .bmignore (#1032), without requiring a configured local_sync_path. Callers preview with ``project_prune_preview`` and pass the confirmed result here. ``--files-from-raw -`` keeps the delete set fixed even if the remote or .bmignore changes while the confirmation prompt is open. @@ -700,100 +551,6 @@ def project_prune( return result.returncode == 0 -def project_bisync( - project: SyncProject, - bucket_name: str, - dry_run: bool = False, - resync: bool = False, - verbose: bool = False, - *, - run: RunFunc = subprocess.run, - is_installed: IsInstalledFunc = is_rclone_installed, - version: tuple[int, int, int] | None = None, - filter_path: Path | None = None, - state_path: Path | None = None, - is_initialized: Callable[[str], bool] = bisync_initialized, -) -> bool: - """Two-way sync: local ↔ cloud. - - Uses rclone bisync with balanced defaults: - - conflict_resolve: newer (auto-resolve to most recent) - - max_delete: 25 (safety limit) - - compare: modtime (ignore size differences from line ending conversions) - - check_access: false (skip for performance) - - Args: - project: Project to sync - bucket_name: S3 bucket name - dry_run: Preview changes without applying - resync: Force resync to establish new baseline - verbose: Show detailed output - - Returns: - True if bisync succeeded, False otherwise - - Raises: - RcloneError: If project has no local_sync_path, needs --resync, or rclone not installed - """ - check_rclone_installed(is_installed=is_installed) - - if not project.local_sync_path: - raise RcloneError(f"Project {project.name} has no local_sync_path configured") - - local_path = Path(project.local_sync_path).expanduser() - remote_path = get_project_remote(project, bucket_name) - filter_path = filter_path or get_bmignore_filter_path() - state_path = state_path or get_project_bisync_state(project.name) - - # Ensure state directory exists - state_path.mkdir(parents=True, exist_ok=True) - - cmd = [ - "rclone", - "bisync", - str(local_path), - remote_path, - *TIGRIS_CONSISTENCY_HEADERS, - "--resilient", - "--conflict-resolve=newer", - "--max-delete=25", - "--compare=modtime", # Ignore size differences from line ending conversions - "--filter-from", - str(filter_path), - "--workdir", - str(state_path), - # Prevent NUL byte padding on virtual filesystems (e.g. Google Drive File Stream) - # See: rclone/rclone#6801 - "--local-no-preallocate", - ] - - # Add --create-empty-src-dirs if rclone version supports it (v1.64+) - version = version if version is not None else get_rclone_version(run=run) - if supports_create_empty_src_dirs(version): - cmd.append("--create-empty-src-dirs") - - if verbose: - cmd.append("--verbose") - else: - cmd.append("--progress") - - if dry_run: - cmd.append("--dry-run") - - if resync: - cmd.append("--resync") - - # Check if first run requires resync - if not resync and not is_initialized(project.name) and not dry_run: - raise RcloneError( - f"First bisync for {project.name} requires --resync to establish baseline.\n" - f"Run: {shell_command('bm', 'project', 'bisync', '--name', project.name, '--resync')}" - ) - - result = run(cmd, text=True) - return result.returncode == 0 - - def project_check( project: SyncProject, bucket_name: str, diff --git a/src/basic_memory/cli/commands/cloud/bisync_commands.py b/src/basic_memory/cli/commands/cloud/rclone_filters.py similarity index 56% rename from src/basic_memory/cli/commands/cloud/bisync_commands.py rename to src/basic_memory/cli/commands/cloud/rclone_filters.py index 030575ca9..5784e975c 100644 --- a/src/basic_memory/cli/commands/cloud/bisync_commands.py +++ b/src/basic_memory/cli/commands/cloud/rclone_filters.py @@ -1,17 +1,12 @@ -"""Cloud bisync utility functions for Basic Memory CLI.""" +"""Convert .bmignore patterns into rclone filter files. + +Personal `push`/`pull`/`check` exclude ignored paths with the regular filter. +`prune` uses the inverted filter, which selects only the ignored paths (#1032). +""" from pathlib import Path -from basic_memory.cli.commands.cloud.api_client import make_api_request -from basic_memory.config import ConfigManager from basic_memory.ignore_utils import create_default_bmignore, get_bmignore_path -from basic_memory.schemas.cloud import MountCredentials, TenantMountInfo - - -class BisyncError(Exception): - """Exception raised for bisync-related errors.""" - - pass def _rclone_exclude_filters(pattern: str) -> list[str]: @@ -48,79 +43,16 @@ def _rclone_include_filters(pattern: str) -> list[str]: return [f"+ {path_pattern}", f"+ {path_pattern}/**"] -def _workspace_id_header(workspace_id: str | None) -> dict[str, str]: - """Header that routes a /tenant/mount/* request to a specific tenant. - - The mount endpoints resolve the workspace from X-Workspace-ID (validating - membership + subscription) and fall back to the user's default tenant when - it is absent — so omitting it preserves the original default-tenant behavior. - """ - return {"X-Workspace-ID": workspace_id} if workspace_id else {} - - -async def get_mount_info(*, workspace_id: str | None = None) -> TenantMountInfo: - """Get tenant mount info (bucket name + tenant id) from the cloud API. - - Args: - workspace_id: Tenant id of the target workspace. When omitted, the API - uses the authenticated user's default tenant. - """ - try: - config_manager = ConfigManager() - config = config_manager.config - host_url = config.cloud_host.rstrip("/") - - response = await make_api_request( - method="GET", - url=f"{host_url}/tenant/mount/info", - headers=_workspace_id_header(workspace_id), - ) - - return TenantMountInfo.model_validate(response.json()) - except Exception as e: - raise BisyncError(f"Failed to get tenant info: {e}") from e - - -async def generate_mount_credentials(tenant_id: str) -> MountCredentials: - """Generate scoped S3 credentials for syncing a specific tenant's bucket. - - Args: - tenant_id: Tenant id whose bucket-scoped credentials to mint. Routed via - X-Workspace-ID so team workspaces get their own bucket's credentials. - """ - try: - config_manager = ConfigManager() - config = config_manager.config - host_url = config.cloud_host.rstrip("/") - - # The mount endpoints resolve X-Workspace-ID by matching the workspace's - # tenant_id, so passing a tenant_id here is the correct routing key. - response = await make_api_request( - method="POST", - url=f"{host_url}/tenant/mount/credentials", - headers=_workspace_id_header(tenant_id), - ) - - return MountCredentials.model_validate(response.json()) - except Exception as e: - raise BisyncError(f"Failed to generate credentials: {e}") from e - - -def convert_bmignore_to_rclone_filters( - *, - force: bool = False, - fail_on_read_error: bool = False, -) -> Path: +def convert_bmignore_to_rclone_filters() -> Path: """Convert .bmignore patterns to rclone filter format. Reads /.bmignore (gitignore-style; the config dir honors BASIC_MEMORY_CONFIG_DIR) and converts it to /.bmignore.rclone (rclone filter format). - Only regenerates if .bmignore has been modified since last conversion, - unless force=True is used for a destructive filter consumer. Destructive - callers also set fail_on_read_error so a guessed fallback filter can never - drive deletion. + Only regenerates if .bmignore has been modified since last conversion. + The filter only narrows additive transfers and comparisons, so a stale + cache or the minimal fallback below can never cause a deletion. Returns: Path to converted rclone filter file @@ -133,7 +65,7 @@ def convert_bmignore_to_rclone_filters( rclone_filter_path = bmignore_path.parent / f"{bmignore_path.name}.rclone" # Skip regeneration if rclone file is newer than bmignore - if rclone_filter_path.exists() and not force: + if rclone_filter_path.exists(): bmignore_mtime = bmignore_path.stat().st_mtime rclone_mtime = rclone_filter_path.stat().st_mtime if rclone_mtime >= bmignore_mtime: @@ -152,9 +84,7 @@ def convert_bmignore_to_rclone_filters( patterns.extend(_rclone_exclude_filters(line)) - except OSError as error: - if fail_on_read_error: - raise BisyncError(f"Failed to read {bmignore_path}: {error}") from error + except OSError: # If we can't read the file, create a minimal filter patterns = ["# Error reading .bmignore, using minimal filters", "- .git", "- .git/**"] @@ -167,9 +97,9 @@ def convert_bmignore_to_rclone_filters( def convert_bmignore_to_rclone_prune_filters() -> Path: """Convert .bmignore patterns into an *inverted* rclone filter for prune. - Where the sync filter excludes ignored paths from a transfer, the prune - filter includes exactly those paths and excludes everything else, so - `rclone lsf` / `rclone delete` operate on the ignored set alone (#1032). + Where the transfer filter excludes ignored paths, the prune filter includes + exactly those paths and excludes everything else, so `rclone lsf` / + `rclone delete` operate on the ignored set alone (#1032). Always regenerated (no mtime caching like the exclude converter), and any read error propagates instead of falling back to minimal filters: this @@ -205,15 +135,3 @@ def convert_bmignore_to_rclone_prune_filters() -> Path: prune_filter_path.write_text("\n".join(patterns) + "\n") return prune_filter_path - - -def get_bisync_filter_path() -> Path: - """Get path to bisync filter file. - - Uses /.bmignore (converted to rclone format). - The file is automatically created with default patterns on first use. - - Returns: - Path to rclone filter file - """ - return convert_bmignore_to_rclone_filters() diff --git a/src/basic_memory/cli/commands/cloud/removed_mirror_commands.py b/src/basic_memory/cli/commands/cloud/removed_mirror_commands.py new file mode 100644 index 000000000..316ba6d70 --- /dev/null +++ b/src/basic_memory/cli/commands/cloud/removed_mirror_commands.py @@ -0,0 +1,112 @@ +"""Migration stubs for the cloud mirror commands removed in 1.0 (#1845). + +`bm cloud sync`, `bm cloud bisync`, and `bm cloud bisync-reset` were deprecated +in #1596 and removed in 1.0. `sync` made Cloud match the local folder, deleting +cloud-only notes, including notes that people and agents created in Cloud. + +The command names stay registered (hidden from help) so scripts and scheduled +jobs that still call them fail with directions instead of Click's generic +"No such command". The stubs read no config or credentials, call no API, and +touch no files. They do not forward to push or pull either: the right +direction and conflict choice depend on what the old job was for. +""" + +from collections.abc import Sequence + +import typer +from rich.console import Console + +from basic_memory.cli.app import cloud_app +from basic_memory.config import resolve_data_dir +from basic_memory.utils import shell_command + +console = Console() + +# Trigger: an old invocation such as `bm cloud bisync --name research --resync`. +# Why: the stubs declare no options, so the flags of the removed commands would +# otherwise fail with a usage error that hides the migration guidance. +# Outcome: every argument is accepted and ignored, and the stub explains the change. +ACCEPT_ANY_ARGS = {"allow_extra_args": True, "ignore_unknown_options": True} + +PROJECT_PLACEHOLDER = "" + + +def _project_name(args: Sequence[str]) -> str: + """Pick the project name out of an old invocation, so the printed commands fit it.""" + for index, arg in enumerate(args): + if arg in ("--name", "--project") and index + 1 < len(args): + return args[index + 1] + for option in ("--name=", "--project="): + if arg.startswith(option): + return arg.removeprefix(option) + # `bisync-reset` took the project as a positional argument. + positional = [arg for arg in args if not arg.startswith("-")] + return positional[0] if positional else PROJECT_PLACEHOLDER + + +def _command(*parts: str) -> str: + """Quote a real project name; leave the placeholder readable.""" + if parts[-1] == PROJECT_PLACEHOLDER: + return f"{shell_command(*parts[:-1])} {PROJECT_PLACEHOLDER}" + return shell_command(*parts) + + +def _exit_with_guidance(command: str, reason: str, name: str) -> None: + """Print the migration guidance for a removed command and exit nonzero.""" + pull = _command("bm", "cloud", "pull", "--name", name) + push = _command("bm", "cloud", "push", "--name", name) + guidance = "\n".join( + [ + f"`bm cloud {command}` was removed in Basic Memory 1.0. {reason}", + "Nothing was transferred or deleted.", + "", + "Preview, then download cloud changes:", + f" {pull} --dry-run", + f" {pull}", + "Preview, then upload local changes:", + f" {push} --dry-run", + f" {push}", + "", + "push and pull never delete files on the destination, and renames are not", + "propagated as moves. If a file differs on both sides, the transfer stops", + "before copying anything. Re-run with --on-conflict keep-local, keep-cloud,", + "or keep-both to choose. `push --on-conflict keep-local` gives local content", + "precedence but keeps files that exist only in Cloud.", + ] + ) + # markup=False: the project name is user text, and Rich markup in it would + # change the commands the user copies. + console.print(guidance, style="yellow", markup=False) + raise typer.Exit(1) + + +@cloud_app.command("sync", hidden=True, context_settings=ACCEPT_ANY_ARGS) +def sync_removed(ctx: typer.Context) -> None: + """Removed in 1.0. Use `bm cloud push` / `bm cloud pull`.""" + _exit_with_guidance( + "sync", + "It mirrored the local folder onto Cloud and deleted cloud-only files.", + _project_name(ctx.args), + ) + + +@cloud_app.command("bisync", hidden=True, context_settings=ACCEPT_ANY_ARGS) +def bisync_removed(ctx: typer.Context) -> None: + """Removed in 1.0. Use `bm cloud pull` / `bm cloud push`.""" + _exit_with_guidance( + "bisync", + "It mirrored both directions and could delete or overwrite files on either side.", + _project_name(ctx.args), + ) + + +@cloud_app.command("bisync-reset", hidden=True, context_settings=ACCEPT_ANY_ARGS) +def bisync_reset_removed(ctx: typer.Context) -> None: + """Removed in 1.0. push and pull keep no sync state.""" + state_dir = resolve_data_dir() / "bisync-state" + _exit_with_guidance( + "bisync-reset", + "push and pull keep no sync state, so there is nothing to reset. Old bisync " + f"state in {state_dir} is no longer used; you can delete it yourself.", + _project_name(ctx.args), + ) diff --git a/src/basic_memory/cli/commands/cloud/upload_command.py b/src/basic_memory/cli/commands/cloud/upload_command.py index b3c161f73..c15acc365 100644 --- a/src/basic_memory/cli/commands/cloud/upload_command.py +++ b/src/basic_memory/cli/commands/cloud/upload_command.py @@ -144,7 +144,7 @@ async def _upload(): # Index project if requested (skip on dry run). # Trigger: upload adds new files the watcher has not observed locally. # Why: force_full ensures those freshly uploaded files are indexed immediately. - # Outcome: upload keeps its eager reindex while sync/bisync stay incremental. + # Outcome: upload reindexes the uploaded files before returning. if index and not dry_run: console.print(f"[blue]Indexing project '{literal(project)}'...[/blue]") try: diff --git a/src/basic_memory/cli/commands/project.py b/src/basic_memory/cli/commands/project.py index 7a2b20120..04804e944 100644 --- a/src/basic_memory/cli/commands/project.py +++ b/src/basic_memory/cli/commands/project.py @@ -17,7 +17,7 @@ from basic_memory.cli.app import app from basic_memory.cli.auth import CLIAuth from basic_memory.cli.commands.cloud.api_client import CloudAPIError, make_api_request -from basic_memory.cli.commands.cloud.bisync_commands import get_mount_info +from basic_memory.cli.commands.cloud.mount_api import get_mount_info from basic_memory.cli.commands.cloud.project_sync import ( _has_cloud_credentials, _require_cloud_credentials, @@ -655,8 +655,8 @@ def _select_attached_row_key( # Push/pull works on every workspace type (rclone on Personal, WebDAV # on Team), so a local sync path is usable everywhere. The JSON keys - # stay for scripts that read them; the mirror commands that were - # Personal-only (sync/bisync) are deprecated (#1596). + # stay for scripts that read them; the Personal-only mirror commands + # (sync/bisync) were removed in 1.0 (#1845). sync_supported = True sync_reason = None local_usage = "sync-supported" @@ -1103,8 +1103,7 @@ async def _add_project(): console.print( f"\n[green]Local sync path configured: {literal(local_sync_path)}[/green]" ) - # Push/pull is the supported sync workflow on every workspace; the - # bisync mirror is deprecated (#1596), so it is not suggested here. + # Push/pull is the transfer workflow on every workspace. # Mirrors `bm cloud sync-setup`. console.print("\nNext steps:") console.print( @@ -1221,16 +1220,9 @@ def remove_project( raise typer.Exit(1) local_path_config = None - bisync_state_path: Path | None = None - if cloud_routed and entry is not None and entry_name is not None and entry.local_sync_path: + if cloud_routed and entry is not None and entry.local_sync_path: local_path_config = entry.local_sync_path - # Bisync state is keyed by the canonical config name, not the form - # the user typed. - from basic_memory.cli.commands.cloud.rclone_commands import get_project_bisync_state - - bisync_state_path = get_project_bisync_state(entry_name) - # Trigger: the delete goes to the cloud. # Why: the cloud service always deletes a project's files on delete # (basic-memory-cloud#2117); files kept under a deleted project were @@ -1334,13 +1326,6 @@ async def _remove_project(): elif local_dir.exists(): console.print(f"[yellow]Local files kept at {literal(local_path_config)}[/yellow]") - # Clean up bisync state if it exists - if bisync_state_path is not None and bisync_state_path.exists(): - import shutil - - shutil.rmtree(bisync_state_path) - console.print("[green]Removed bisync state[/green]") - except Exception as e: # str() of httpx transport errors is often empty (#1034) — never print a blank error. console.print(f"[red]Error removing project: {literal(str(e) or repr(e))}[/red]") diff --git a/src/basic_memory/man/bm.1 b/src/basic_memory/man/bm.1 index 5639a10d5..553e6a19c 100644 --- a/src/basic_memory/man/bm.1 +++ b/src/basic_memory/man/bm.1 @@ -85,7 +85,7 @@ run afterwards. .TP .B bm cloud -Authenticate, sync (push/pull; sync/bisync are deprecated), snapshots, and team workspace +Authenticate, transfer files (push/pull), snapshots, and team workspace administration. .PP Infrastructure: diff --git a/tests/cli/cloud/test_bmignore_sync_filter_refresh.py b/tests/cli/cloud/test_bmignore_sync_filter_refresh.py deleted file mode 100644 index 3b4372f89..000000000 --- a/tests/cli/cloud/test_bmignore_sync_filter_refresh.py +++ /dev/null @@ -1,88 +0,0 @@ -"""Destructive one-way sync must never use a stale .bmignore filter.""" - -import os -from pathlib import Path -from types import SimpleNamespace - -import pytest - -from basic_memory.cli.commands.cloud import rclone_commands -from basic_memory.cli.commands.cloud.bisync_commands import ( - BisyncError, - convert_bmignore_to_rclone_filters, -) -from basic_memory.cli.commands.cloud.rclone_commands import SyncProject, project_sync -from basic_memory.ignore_utils import get_bmignore_path - - -def test_force_refresh_bypasses_newer_filter_cache(config_home) -> None: - """A destructive caller can rebuild even when cache mtimes are misleading.""" - bmignore = get_bmignore_path() - bmignore.parent.mkdir(parents=True, exist_ok=True) - bmignore.write_text("old-pattern\n", encoding="utf-8") - filter_path = convert_bmignore_to_rclone_filters() - - bmignore.write_text("new-pattern\n", encoding="utf-8") - future = filter_path.stat().st_mtime + 60 - os.utime(filter_path, (future, future)) - - assert "old-pattern" in convert_bmignore_to_rclone_filters().read_text() - refreshed = convert_bmignore_to_rclone_filters(force=True) - assert "new-pattern" in refreshed.read_text() - assert "old-pattern" not in refreshed.read_text() - - -def test_project_sync_forces_current_bmignore_filter(tmp_path, monkeypatch) -> None: - """The --delete-excluded mirror requests a freshly generated filter.""" - filter_path = tmp_path / ".bmignore.rclone" - filter_path.write_text("- current-pattern\n", encoding="utf-8") - filter_requests: list[tuple[bool, bool]] = [] - - def fake_filter_path(*, force: bool = False, fail_on_read_error: bool = False): - filter_requests.append((force, fail_on_read_error)) - return filter_path - - monkeypatch.setattr(rclone_commands, "get_bmignore_filter_path", fake_filter_path) - project = SyncProject(name="research", path="/research", local_sync_path=str(tmp_path)) - - result = project_sync( - project, - "bucket", - run=lambda *args, **kwargs: SimpleNamespace(returncode=0, stdout="", stderr=""), - is_installed=lambda: True, - ) - - assert result is True - assert filter_requests == [(True, True)] - - -def test_destructive_filter_refresh_fails_when_bmignore_is_unreadable( - config_home, monkeypatch -) -> None: - """A destructive mirror must not fall back to guessed ignore rules.""" - bmignore = get_bmignore_path() - bmignore.parent.mkdir(parents=True, exist_ok=True) - bmignore.write_text("private/**\n", encoding="utf-8") - original_open = Path.open - - def fail_bmignore_read(path: Path, *args, **kwargs): - if path == bmignore: - raise PermissionError("permission denied") - return original_open(path, *args, **kwargs) - - monkeypatch.setattr(Path, "open", fail_bmignore_read) - - with pytest.raises(BisyncError, match="Failed to read .*permission denied"): - convert_bmignore_to_rclone_filters(force=True, fail_on_read_error=True) - - -def test_rclone_filter_reads_a_bmignore_with_a_utf8_bom(config_home) -> None: - """Cloud push and pull filters must not keep a BOM on the first rule (#1946).""" - bmignore = get_bmignore_path() - bmignore.parent.mkdir(parents=True, exist_ok=True) - bmignore.write_bytes(b"\xef\xbb\xbfprivate\n") - - filters = convert_bmignore_to_rclone_filters(force=True).read_text(encoding="utf-8") - - assert "" not in filters - assert "- private" in filters.splitlines() diff --git a/tests/cli/cloud/test_project_sync_command.py b/tests/cli/cloud/test_project_sync_command.py index 36f7eebac..177978752 100644 --- a/tests/cli/cloud/test_project_sync_command.py +++ b/tests/cli/cloud/test_project_sync_command.py @@ -1,4 +1,4 @@ -"""Tests for cloud sync and bisync command behavior.""" +"""Tests for cloud transfer, prune, check, and setup command behavior.""" import importlib import re @@ -33,10 +33,10 @@ def _plain(text: str) -> str: @pytest.mark.parametrize( "command", - ["sync", "bisync", "check", "bisync-reset", "prune"], + ["check", "prune"], ) -def test_cloud_mirror_command_help_marks_personal_workspaces_only(command): - """Mirror-family help must say Personal-only and point Team users at push/pull (#851).""" +def test_cloud_personal_only_command_help_points_at_push_pull(command): + """Personal-only command help must say Personal-only and point Team users at push/pull (#851).""" result = runner.invoke(app, ["cloud", command, "--help"]) assert result.exit_code == 0, result.output @@ -46,248 +46,8 @@ def test_cloud_mirror_command_help_marks_personal_workspaces_only(command): assert "bm cloud push" in output -@pytest.mark.parametrize( - "argv", - [ - ["cloud", "sync", "--name", "research"], - ["cloud", "bisync", "--name", "research"], - # --project is an alias for --name (issue #817) - ["cloud", "sync", "--project", "research"], - ["cloud", "bisync", "--project", "research"], - ], -) -def test_cloud_sync_commands_skip_explicit_cloud_project_sync(monkeypatch, argv, config_manager): - """Cloud sync commands should not trigger an extra explicit cloud project sync.""" - project_sync_command = importlib.import_module("basic_memory.cli.commands.cloud.project_sync") - - config = config_manager.load_config() - config.set_project_mode("research", ProjectMode.CLOUD) - config_manager.save_config(config) - - monkeypatch.setattr(project_sync_command, "_require_cloud_credentials", lambda _config: None) - target_workspace = _workspace("personal-tenant", "personal", "personal", is_default=True) - monkeypatch.setattr( - project_sync_command, - "_require_personal_workspace", - lambda _name, _config, **_kwargs: target_workspace, - ) - monkeypatch.setattr( - project_sync_command, - "get_mount_info", - lambda **_kwargs: _async_value(SimpleNamespace(bucket_name="tenant-bucket")), - ) - monkeypatch.setattr( - project_sync_command, - "_get_cloud_project", - lambda _name, **_kwargs: _async_value( - SimpleNamespace(name="research", external_id="external-project-id", path="research") - ), - ) - monkeypatch.setattr( - project_sync_command, - "_get_sync_project", - lambda _name, _config, _project_data, **_kwargs: ( - SimpleNamespace(name="research"), - "/tmp/research", - ), - ) - monkeypatch.setattr(project_sync_command, "project_sync", lambda *args, **kwargs: True) - monkeypatch.setattr(project_sync_command, "project_bisync", lambda *args, **kwargs: True) - - result = runner.invoke(app, argv) - - assert result.exit_code == 0, result.output - assert "Database sync initiated" not in result.output - - -def test_cloud_bisync_fails_fast_when_sync_entry_disappears(monkeypatch, config_manager): - """Bisync should raise a runtime error when validated sync config vanishes before persistence.""" - project_sync_command = importlib.import_module("basic_memory.cli.commands.cloud.project_sync") - - config = config_manager.load_config() - config.projects.pop("research", None) - config_manager.save_config(config) - - monkeypatch.setattr(project_sync_command, "_require_cloud_credentials", lambda _config: None) - monkeypatch.setattr( - project_sync_command, "_require_personal_workspace", lambda _name, _config, **_kwargs: None - ) - monkeypatch.setattr( - project_sync_command, - "get_mount_info", - lambda: _async_value(SimpleNamespace(bucket_name="tenant-bucket")), - ) - monkeypatch.setattr( - project_sync_command, - "_get_cloud_project", - lambda _name: _async_value( - SimpleNamespace(name="research", external_id="external-project-id", path="research") - ), - ) - monkeypatch.setattr( - project_sync_command, - "_get_sync_project", - lambda _name, _config, _project_data: (SimpleNamespace(name="research"), "/tmp/research"), - ) - monkeypatch.setattr(project_sync_command, "project_bisync", lambda *args, **kwargs: True) - - result = runner.invoke(app, ["cloud", "bisync", "--name", "research"]) - - assert result.exit_code == 1, result.output - assert "unexpectedly missing after validation" in result.output - - -@pytest.mark.parametrize( - "argv", - [ - ["cloud", "bisync", "--name", "research"], - ["cloud", "bisync-reset", "research"], - ], -) -def test_cloud_bisync_commands_block_organization_workspace(monkeypatch, argv, config_manager): - """Deprecated bisync commands refuse Team workspaces before setup/execution.""" - project_sync_command = importlib.import_module("basic_memory.cli.commands.cloud.project_sync") - - config = config_manager.load_config() - config.cloud_api_key = "bmc_test" - config.projects["research"] = ProjectEntry( - path="/tmp/research", - mode=ProjectMode.CLOUD, - workspace_id="team-tenant", - local_sync_path="/tmp/research", - ) - config_manager.save_config(config) - - monkeypatch.setattr( - project_sync_command, - "get_available_workspaces", - lambda: _async_value([_workspace("team-tenant", "organization", "team")]), - ) - monkeypatch.setattr( - project_sync_command, - "get_mount_info", - lambda: pytest.fail("workspace guard should run before mount lookup"), - ) - monkeypatch.setattr( - project_sync_command, - "get_project_bisync_state", - lambda _name: pytest.fail("workspace guard should run before bisync state lookup"), - ) - - result = runner.invoke(app, argv) - - assert result.exit_code == 1, result.output - output = " ".join(result.output.split()) - assert "is deprecated and will be removed in a future release" in output - assert "bm cloud pull --name research" in output - assert "bm cloud push --name research" in output - - -def test_cloud_sync_blocks_organization_workspace(monkeypatch, config_manager): - """The deprecated mirror `sync` blocks Team workspaces with the push/pull commands.""" - project_sync_command = importlib.import_module("basic_memory.cli.commands.cloud.project_sync") - - config = config_manager.load_config() - config.cloud_api_key = "bmc_test" - config.projects["research"] = ProjectEntry( - path="/tmp/research", - mode=ProjectMode.CLOUD, - workspace_id="team-tenant", - local_sync_path="/tmp/research", - ) - config_manager.save_config(config) - - monkeypatch.setattr( - project_sync_command, - "get_available_workspaces", - lambda: _async_value([_workspace("team-tenant", "organization", "team")]), - ) - monkeypatch.setattr( - project_sync_command, - "get_mount_info", - lambda: pytest.fail("workspace guard should run before mount lookup"), - ) - - result = runner.invoke(app, ["cloud", "sync", "--name", "research"]) - - assert result.exit_code == 1, result.output - output = " ".join(result.output.split()) - assert "`bm cloud sync` is deprecated and does not run on Team workspaces" in output - assert "bm cloud push --name research" in output - assert "bm cloud pull --name research" in output - - -def test_cloud_sync_allows_personal_workspace(monkeypatch, config_manager): - """Personal workspaces keep the one-way mirror sync available.""" - project_sync_command = importlib.import_module("basic_memory.cli.commands.cloud.project_sync") - routing: dict[str, Any] = {} - - config = config_manager.load_config() - config.cloud_api_key = "bmc_test" - config.projects["research"] = ProjectEntry( - path="/tmp/research", - mode=ProjectMode.CLOUD, - workspace_id="personal-tenant", - local_sync_path="/tmp/research", - ) - config_manager.save_config(config) - - monkeypatch.setattr( - project_sync_command, - "get_available_workspaces", - lambda: _async_value([_workspace("personal-tenant", "personal", "personal-alt")]), - ) - - def _mount_info(**kwargs): - routing["mount_workspace_id"] = kwargs.get("workspace_id") - return _async_value(SimpleNamespace(bucket_name="tenant-bucket")) - - monkeypatch.setattr( - project_sync_command, - "get_mount_info", - _mount_info, - ) - - def _cloud_project(_name, **kwargs): - routing["project_workspace_id"] = kwargs.get("workspace_id") - return _async_value( - SimpleNamespace(name="research", external_id="external-project-id", path="research") - ) - - monkeypatch.setattr( - project_sync_command, - "_get_cloud_project", - _cloud_project, - ) - - def _sync_project(_name, _config, _project_data, **kwargs): - routing["remote_name"] = kwargs.get("remote_name") - return SimpleNamespace(name="research"), "/tmp/research" - - monkeypatch.setattr( - project_sync_command, - "_get_sync_project", - _sync_project, - ) - monkeypatch.setattr(project_sync_command, "project_sync", lambda *args, **kwargs: True) - - result = runner.invoke(app, ["cloud", "sync", "--name", "research"]) - - assert result.exit_code == 0, result.output - assert "research synced successfully" in result.output - # Still runs on Personal, but warns on every run (#1596). - output = " ".join(result.output.split()) - assert "`bm cloud sync` is deprecated" in output - assert "bm cloud push --name research" in output - assert routing == { - "mount_workspace_id": "personal-tenant", - "project_workspace_id": "personal-tenant", - "remote_name": "basic-memory-cloud-personal-alt", - } - - def test_require_personal_workspace_allows_personal_workspace(monkeypatch, config_manager): - """Personal workspaces keep the existing rclone sync path available.""" + """Personal workspaces pass the prune guard.""" project_sync_command = importlib.import_module("basic_memory.cli.commands.cloud.project_sync") config = config_manager.load_config() @@ -428,28 +188,6 @@ def test_require_personal_workspace_reports_ambiguous_workspace(monkeypatch, con assert exc_info.value.exit_code == 1 -def test_bisync_reset_skips_workspace_check_without_credentials(monkeypatch, tmp_path): - """Resetting local bisync state stays harmless when no cloud credentials exist.""" - project_sync_command = importlib.import_module("basic_memory.cli.commands.cloud.project_sync") - - monkeypatch.setattr( - project_sync_command, - "get_available_workspaces", - lambda: pytest.fail("workspace lookup requires cloud credentials"), - ) - monkeypatch.setattr( - project_sync_command, - "get_project_bisync_state", - lambda _name: tmp_path / "missing-state", - ) - - result = runner.invoke(app, ["cloud", "bisync-reset", "research"]) - - assert result.exit_code == 0, result.output - assert "No bisync state found for project 'research'" in result.output - assert "`bm cloud bisync-reset` is deprecated" in " ".join(result.output.split()) - - def _stub_transfer_env( monkeypatch, module, *, plan, transfer_result=True, recorder=None, workspace=None ): @@ -1135,7 +873,7 @@ def test_cloud_prune_blocks_organization_workspace(monkeypatch, config_manager): assert result.exit_code == 1, result.output output = " ".join(result.output.split()) assert "The prune operation" in output - # prune is not a deprecated mirror command; only sync/bisync warn (#1596). + # prune is a supported Personal-only command, not a removed mirror stub. assert "is deprecated" not in output assert "only supported on Personal workspaces" in output assert "bm cloud push --name research" in output @@ -1250,86 +988,6 @@ def _workspace( ) -@pytest.mark.parametrize("command", ["sync", "bisync", "bisync-reset"]) -def test_mirror_commands_are_marked_deprecated_in_help(command): - """Help output labels the rclone mirror commands deprecated (#1596).""" - result = runner.invoke(app, ["cloud", "--help"], env={"COLUMNS": "200"}) - - assert result.exit_code == 0, result.output - # CI sets FORCE_COLOR, so strip escape codes before reading table rows. - rows = re.sub(r"\x1b\[[0-9;]*m", "", result.output).splitlines() - line = next(line for line in rows if line.strip("│ ").startswith(f"{command} ")) - assert "deprecated" in line.lower() - - -@pytest.mark.parametrize("command", ["sync", "bisync"]) -def test_mirror_commands_show_migration_notice_without_credentials(monkeypatch, command): - """A logged-out run still names pull/push before the credential error (#1596).""" - project_sync_command = importlib.import_module("basic_memory.cli.commands.cloud.project_sync") - monkeypatch.setattr(project_sync_command, "_has_cloud_credentials", lambda _config: False) - - result = runner.invoke(app, ["cloud", command, "--name", "research"]) - - output = _plain(result.output) - assert result.exit_code == 1, result.output - assert f"`bm cloud {command}` is deprecated" in output - assert "bm cloud pull" in output - assert "cloud credentials are required" in output - - -@pytest.mark.parametrize("command", ["sync", "bisync"]) -def test_migration_notice_keeps_markup_in_project_names(monkeypatch, command): - """Rich must not eat a bracketed project name from the suggested command.""" - project_sync_command = importlib.import_module("basic_memory.cli.commands.cloud.project_sync") - monkeypatch.setattr(project_sync_command, "_has_cloud_credentials", lambda _config: False) - - result = runner.invoke(app, ["cloud", command, "--name", "[bold]oops[/bold]"]) - - assert "bm cloud pull --name '[bold]oops[/bold]'" in _plain(result.output) - - -@pytest.mark.parametrize( - "argv", - [ - ["cloud", "sync", "--name", "research"], - ["cloud", "bisync", "--name", "research"], - ["cloud", "bisync-reset", "research"], - ], -) -def test_mirror_commands_print_one_deprecation_notice(monkeypatch, tmp_path, argv): - """Only our notice prints; Click's generic DeprecationWarning line is dropped (#1720).""" - project_sync_command = importlib.import_module("basic_memory.cli.commands.cloud.project_sync") - monkeypatch.setattr(project_sync_command, "_has_cloud_credentials", lambda _config: False) - monkeypatch.setattr( - project_sync_command, - "get_project_bisync_state", - lambda _name: tmp_path / "missing-state", - ) - - result = runner.invoke(app, argv) - - output = _plain(result.output) - assert "DeprecationWarning" not in output - assert output.count("is deprecated and will be removed") == 1 - - -@pytest.mark.parametrize("name", ["proj [x]", "a[/b]c", "[bold]x[/bold]"]) -def test_bisync_reset_prints_bracketed_project_names_verbatim(monkeypatch, tmp_path, name): - """Bracketed names survive in status lines; a closing tag used to crash (#1720).""" - project_sync_command = importlib.import_module("basic_memory.cli.commands.cloud.project_sync") - monkeypatch.setattr(project_sync_command, "_has_cloud_credentials", lambda _config: False) - monkeypatch.setattr( - project_sync_command, - "get_project_bisync_state", - lambda _name: tmp_path / "missing-state", - ) - - result = runner.invoke(app, ["cloud", "bisync-reset", name]) - - assert result.exit_code == 0, result.output - assert f"No bisync state found for project '{name}'" in _plain(result.output) - - def test_workspace_resolution_error_prints_bracketed_name_verbatim( monkeypatch, config_manager, capsys ): diff --git a/tests/cli/cloud/test_rclone_config_and_bmignore_filters.py b/tests/cli/cloud/test_rclone_config_and_bmignore_filters.py index b3c8b4463..bff0c0727 100644 --- a/tests/cli/cloud/test_rclone_config_and_bmignore_filters.py +++ b/tests/cli/cloud/test_rclone_config_and_bmignore_filters.py @@ -1,9 +1,10 @@ import os import time +from pathlib import Path import pytest -from basic_memory.cli.commands.cloud.bisync_commands import ( +from basic_memory.cli.commands.cloud.rclone_filters import ( convert_bmignore_to_rclone_filters, convert_bmignore_to_rclone_prune_filters, ) @@ -101,6 +102,27 @@ def test_convert_bmignore_to_rclone_filters_is_cached_when_up_to_date(config_hom assert second.stat().st_mtime >= first_mtime +def test_convert_bmignore_to_rclone_filters_falls_back_when_unreadable(config_home, monkeypatch): + """An unreadable .bmignore still yields a filter that keeps .git out of transfers.""" + bmignore = get_bmignore_path() + bmignore.parent.mkdir(parents=True, exist_ok=True) + bmignore.write_text("private/**\n", encoding="utf-8") + original_open = Path.open + + def fail_bmignore_read(path: Path, *args, **kwargs): + if path == bmignore: + raise PermissionError("permission denied") + return original_open(path, *args, **kwargs) + + monkeypatch.setattr(Path, "open", fail_bmignore_read) + + content = convert_bmignore_to_rclone_filters().read_text(encoding="utf-8") + + assert "# Error reading .bmignore, using minimal filters" in content + assert "- .git/**" in content + assert "private" not in content + + def test_convert_bmignore_to_prune_filters_inverts_patterns(config_home): """Prune filter includes exactly what the sync filter excludes (#1032).""" bmignore = get_bmignore_path() @@ -228,3 +250,15 @@ def test_rclone_remote_exists(config_home): assert rclone_remote_exists("basic-memory-cloud-acme") is False configure_rclone_remote(access_key="ak", secret_key="sk", remote_name="basic-memory-cloud-acme") assert rclone_remote_exists("basic-memory-cloud-acme") is True + + +def test_rclone_filter_reads_a_bmignore_with_a_utf8_bom(config_home) -> None: + """Cloud push and pull filters must not keep a BOM on the first rule (#1946).""" + bmignore = get_bmignore_path() + bmignore.parent.mkdir(parents=True, exist_ok=True) + bmignore.write_bytes(b"\xef\xbb\xbfprivate\n") + + filters = convert_bmignore_to_rclone_filters().read_text(encoding="utf-8") + + assert "" not in filters + assert "- private" in filters.splitlines() diff --git a/tests/cli/cloud/test_removed_mirror_commands.py b/tests/cli/cloud/test_removed_mirror_commands.py new file mode 100644 index 000000000..245ee5a41 --- /dev/null +++ b/tests/cli/cloud/test_removed_mirror_commands.py @@ -0,0 +1,140 @@ +"""The cloud mirror commands removed in 1.0 only print migration guidance (#1845).""" + +import json +import re +from pathlib import Path + +import httpx +import pytest +from typer.testing import CliRunner + +from basic_memory.cli.main import app + +runner = CliRunner() + +REMOVED_INVOCATIONS = [ + ["cloud", "sync", "--name", "research"], + ["cloud", "sync", "--project", "research", "--dry-run", "--verbose"], + ["cloud", "bisync", "--name", "research", "--resync"], + ["cloud", "bisync", "--name=research", "--dry-run"], + ["cloud", "bisync-reset", "research"], +] + + +def _plain(text: str) -> str: + """Strip console styling and wrapping so assertions read against the words.""" + return " ".join(re.sub(r"\x1b\[[0-9;]*m", "", text).split()) + + +def _tree(root: Path) -> dict[str, bytes]: + """Every user file under root with its bytes, to prove a command changed nothing. + + The CLI callback opens the local index database before any `bm` subcommand + runs, so the database files are not evidence about the removed commands. + """ + return { + path.relative_to(root).as_posix(): path.read_bytes() + for path in sorted(root.rglob("*")) + if path.is_file() and not path.name.startswith("memory.db") + } + + +@pytest.fixture +def mirror_user(tmp_path, monkeypatch) -> Path: + """A logged-in user with a synced project and old bisync state on disk.""" + home = tmp_path / "home" + config_dir = home / ".basic-memory" + notes = home / "notes" + state = config_dir / "bisync-state" / "research" + for directory in (config_dir, notes, state): + directory.mkdir(parents=True) + + (notes / "only-local.md").write_text("# Only local\n") + (state / "listing.lst").write_text("old bisync listing\n") + (config_dir / "config.json").write_text( + json.dumps( + { + "cloud_api_key": "bmc_test", + "projects": { + "research": { + "path": str(notes), + "mode": "cloud", + "local_sync_path": str(notes), + "bisync_initialized": True, + } + }, + "default_project": "research", + } + ) + ) + + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("BASIC_MEMORY_CONFIG_DIR", str(config_dir)) + + # Any cloud call (mount info, credential minting, project lookup, WebDAV) + # goes through httpx; a removed command must never reach the network. + async def _no_network(*args, **kwargs): + pytest.fail("a removed mirror command made an HTTP request") + + monkeypatch.setattr(httpx.AsyncClient, "send", _no_network) + return home + + +@pytest.mark.parametrize("argv", REMOVED_INVOCATIONS) +def test_removed_mirror_command_exits_nonzero_and_changes_nothing(mirror_user, argv): + """Old invocations fail with guidance, and no file, credential, or state changes.""" + before = _tree(mirror_user) + + result = runner.invoke(app, argv) + + assert result.exit_code == 1, result.output + output = _plain(result.output) + assert f"`bm cloud {argv[1]}` was removed in Basic Memory 1.0" in output + assert "Nothing was transferred or deleted." in output + assert "bm cloud pull --name research --dry-run" in output + assert "bm cloud push --name research --dry-run" in output + assert "--on-conflict keep-local, keep-cloud, or keep-both" in output + assert "keeps files that exist only in Cloud" in output + assert _tree(mirror_user) == before + + +def test_bisync_reset_points_at_old_state_without_deleting_it(mirror_user): + """The old state directory is named for manual cleanup and left in place.""" + state_dir = mirror_user / ".basic-memory" / "bisync-state" + + # A wide console keeps Rich from wrapping the long temp path mid-word. + result = runner.invoke(app, ["cloud", "bisync-reset", "research"], env={"COLUMNS": "400"}) + + assert result.exit_code == 1, result.output + assert f"Old bisync state in {state_dir} is no longer used" in _plain(result.output) + assert (state_dir / "research" / "listing.lst").exists() + + +def test_removed_mirror_command_without_project_uses_placeholder(mirror_user): + """With no project to reuse, the printed commands show where the name goes.""" + result = runner.invoke(app, ["cloud", "sync"]) + + assert result.exit_code == 1, result.output + assert "bm cloud push --name " in _plain(result.output) + + +@pytest.mark.parametrize("name", ["My Notes", "[bold]x[/bold]"]) +def test_removed_mirror_command_quotes_project_names_verbatim(mirror_user, name): + """Printed commands survive copy-paste: shell-quoted, and Rich markup kept literal.""" + result = runner.invoke(app, ["cloud", "bisync", "--name", name]) + + assert result.exit_code == 1, result.output + assert f"bm cloud pull --name '{name}'" in _plain(result.output) + + +def test_removed_mirror_commands_are_hidden_from_cloud_help(): + """Help lists push/pull, not the removed mirror commands.""" + result = runner.invoke(app, ["cloud", "--help"], env={"COLUMNS": "200"}) + + assert result.exit_code == 0, result.output + commands = { + line.strip("│ ").split(" ")[0] + for line in re.sub(r"\x1b\[[0-9;]*m", "", result.output).splitlines() + } + assert {"push", "pull"} <= commands + assert not {"sync", "bisync", "bisync-reset"} & commands diff --git a/tests/cli/test_project_add_remedy_matrix.py b/tests/cli/test_project_add_remedy_matrix.py index 0f09d21b1..45ab5d7e0 100644 --- a/tests/cli/test_project_add_remedy_matrix.py +++ b/tests/cli/test_project_add_remedy_matrix.py @@ -29,8 +29,8 @@ from basic_memory.cli.main import app as cli_app from basic_memory.schemas.cloud import WorkspaceInfo -# The package exposes a *function* named `project_sync`, which shadows the -# submodule, so the module object has to be imported explicitly. +# The cloud package star-imports its command modules, so import the module +# object explicitly to patch its collaborators. project_sync_cmd = importlib.import_module("basic_memory.cli.commands.cloud.project_sync") runner = CliRunner() @@ -175,7 +175,7 @@ def cloud_transfer(monkeypatch): """Let the cloud transfer commands run their guards, then stop before the network. The question each row asks is whether the printed command is *accepted* for - this project -- a Team workspace refuses `bisync` before doing any work -- so + this project -- the removed `bisync` refuses before doing any work -- so the workspace guard stays real and only the transfer is stubbed. """ transfers: list[str] = [] @@ -376,34 +376,16 @@ def test_the_printed_remedy_actually_works( ) -def test_a_team_workspace_really_does_refuse_the_personal_only_mirror( - monkeypatch, cloud_credentials, cloud_transfer -): - """Control for the Team rows: the command we stopped advising does dead-end. +def test_the_removed_mirror_really_does_dead_end(): + """Control for the matrix: the command we stopped advising does dead-end. - Without this, the Team rows above would pass even if `bisync` were harmless - there, and would not be evidence of anything. + Without this, rows that check the remedy is push/pull rather than `bisync` + would pass even if `bisync` still worked, and would not be evidence of anything. """ - - async def _team(_name: str, _config: Any) -> WorkspaceInfo: - return WorkspaceInfo( - tenant_id="ws-123", - workspace_type="organization", - slug="ws", - name="Workspace", - role="owner", - is_default=True, - ) - - monkeypatch.setattr(project_sync_cmd, "_get_workspace_for_project", _team) - monkeypatch.setattr(project_sync_cmd, "_require_cloud_credentials", lambda _config: None) - result = runner.invoke(cli_app, ["cloud", "bisync", "--name", PROJECT], env=WIDE_TERMINAL_ENV) assert result.exit_code == 1 - assert "`bm cloud bisync` is deprecated and does not run on Team workspaces" in flat( - result.output - ) + assert "`bm cloud bisync` was removed in Basic Memory 1.0" in flat(result.output) # --- Convergence --- diff --git a/tests/cli/test_project_remove_cloud_stub.py b/tests/cli/test_project_remove_cloud_stub.py index 6eb739f26..f4559b165 100644 --- a/tests/cli/test_project_remove_cloud_stub.py +++ b/tests/cli/test_project_remove_cloud_stub.py @@ -15,7 +15,6 @@ from typer.testing import CliRunner from basic_memory.cli.app import app -from basic_memory.cli.commands.cloud import rclone_commands from basic_memory.mcp.clients.project import ProjectClient # Importing registers project subcommands on the shared app instance. @@ -165,55 +164,20 @@ def test_auto_routed_cloud_delete_cleans_local_sync_artifacts( }, }, ) - bisync_state = tmp_path / "bisync-state" / "research" + # Old bisync state from before 1.0 belongs to the user; removal leaves it (#1845). + bisync_state = tmp_path / ".basic-memory" / "bisync-state" / "research" bisync_state.mkdir(parents=True) - monkeypatch.setattr( - rclone_commands, "get_project_bisync_state", lambda project_name: bisync_state - ) + (bisync_state / "listing.lst").write_text("old listing\n") result = runner.invoke(app, ["project", "remove", "research", "--yes"]) assert result.exit_code == 0, result.stdout - assert not bisync_state.exists(), "stale bisync state would let a recreated name skip --resync" + assert (bisync_state / "listing.lst").exists(), "removal never deletes old bisync state" assert local_sync.exists(), "the local sync directory stays without --delete-local-files" assert "Local files kept at" in _flat(result.stdout) assert "research" not in _projects(config_file) -def test_bisync_state_cleanup_uses_the_canonical_entry_name( - tmp_path, monkeypatch, runner, cloud_delete -): - """Removing `My Research` as `my-research` must clear `bisync-state/My Research`.""" - local_sync = tmp_path / "research-sync" - local_sync.mkdir() - _write_config( - tmp_path, - monkeypatch, - { - "main": {"path": str(tmp_path / "main"), "mode": "local"}, - "My Research": { - "path": str(local_sync), - "mode": "cloud", - "workspace_id": "team-drew", - "local_sync_path": str(local_sync), - "bisync_initialized": True, - }, - }, - ) - states = {"My Research": tmp_path / "bisync-state" / "My Research"} - states["My Research"].mkdir(parents=True) - monkeypatch.setattr( - rclone_commands, - "get_project_bisync_state", - lambda project_name: states.get(project_name, tmp_path / "bisync-state" / project_name), - ) - - result = runner.invoke(app, ["project", "remove", "my-research", "--yes"]) - - assert result.exit_code == 0, result.stdout - assert not states["My Research"].exists() - - def test_explicit_local_route_leaves_config_removal_to_the_local_service( tmp_path, monkeypatch, runner, cloud_delete ): diff --git a/tests/test_rclone_commands.py b/tests/test_rclone_commands.py index fd93aefee..f78d13dd7 100644 --- a/tests/test_rclone_commands.py +++ b/tests/test_rclone_commands.py @@ -11,16 +11,11 @@ conflict_copy_name, ) from basic_memory.cli.commands.cloud.rclone_commands import ( - MIN_RCLONE_VERSION_EMPTY_DIRS, RcloneError, SyncProject, _parse_check_combined, - bisync_initialized, check_rclone_installed, - get_project_bisync_state, get_project_remote, - get_rclone_version, - project_bisync, project_check, project_copy, project_copy_file, @@ -28,9 +23,7 @@ project_ls, project_prune, project_prune_preview, - project_sync, project_transfer, - supports_create_empty_src_dirs, ) from typing import Any @@ -58,7 +51,7 @@ def _assert_has_consistency_headers(cmd: list[str]) -> None: """Assert the rclone command includes Tigris consistency headers. Uses --header (global flag) so the header applies to ALL HTTP transactions, - including S3 list requests that bisync issues before any download/upload. + including S3 list requests that check and lsf issue before any download/upload. """ assert "--header" in cmd header_idx = cmd.index("--header") @@ -110,301 +103,6 @@ def test_get_project_remote_strips_app_data_prefix(): assert get_project_remote(project, "my-bucket") == "basic-memory-cloud:my-bucket/research" -def test_get_project_bisync_state(monkeypatch): - monkeypatch.delenv("BASIC_MEMORY_CONFIG_DIR", raising=False) - state_path = get_project_bisync_state("research") - expected = Path.home() / ".basic-memory" / "bisync-state" / "research" - assert state_path == expected - - -def test_get_project_bisync_state_honors_basic_memory_config_dir(tmp_path, monkeypatch): - """Regression guard for #742: bisync state dir follows BASIC_MEMORY_CONFIG_DIR.""" - custom_dir = tmp_path / "instance-w" / "state" - monkeypatch.setenv("BASIC_MEMORY_CONFIG_DIR", str(custom_dir)) - - assert get_project_bisync_state("research") == custom_dir / "bisync-state" / "research" - - -def test_bisync_initialized_false_when_not_exists(tmp_path, monkeypatch): - monkeypatch.setattr( - "basic_memory.cli.commands.cloud.rclone_commands.get_project_bisync_state", - lambda project_name: tmp_path / project_name, - ) - assert bisync_initialized("research") is False - - -def test_bisync_initialized_false_when_empty(tmp_path, monkeypatch): - state_dir = tmp_path / "research" - state_dir.mkdir() - monkeypatch.setattr( - "basic_memory.cli.commands.cloud.rclone_commands.get_project_bisync_state", - lambda project_name: tmp_path / project_name, - ) - assert bisync_initialized("research") is False - - -def test_bisync_initialized_true_when_has_files(tmp_path, monkeypatch): - state_dir = tmp_path / "research" - state_dir.mkdir() - (state_dir / "state.lst").touch() - monkeypatch.setattr( - "basic_memory.cli.commands.cloud.rclone_commands.get_project_bisync_state", - lambda project_name: tmp_path / project_name, - ) - assert bisync_initialized("research") is True - - -def test_project_sync_success(tmp_path): - runner = _Runner(returncode=0) - filter_path = _write_filter_file(tmp_path) - project = SyncProject(name="research", path="/research", local_sync_path="/tmp/research") - - result = project_sync( - project, - "my-bucket", - dry_run=True, - run=runner, - is_installed=lambda: True, - filter_path=filter_path, - ) - - assert result is True - assert len(runner.calls) == 1 - cmd, kwargs = runner.calls[0] - assert cmd[:2] == ["rclone", "sync"] - assert Path(cmd[2]) == Path("/tmp/research") - assert cmd[3] == "basic-memory-cloud:my-bucket/research" - _assert_has_consistency_headers(cmd) - assert "--filter-from" in cmd - assert str(filter_path) in cmd - assert "--dry-run" in cmd - assert kwargs["text"] is True - - -def test_project_sync_with_verbose(tmp_path): - runner = _Runner(returncode=0) - filter_path = _write_filter_file(tmp_path) - project = SyncProject( - name="research", path="app/data/research", local_sync_path="/tmp/research" - ) - - project_sync( - project, - "my-bucket", - verbose=True, - run=runner, - is_installed=lambda: True, - filter_path=filter_path, - ) - - cmd, _ = runner.calls[0] - assert "--verbose" in cmd - assert "--progress" not in cmd - - -def test_project_sync_with_progress(tmp_path): - runner = _Runner(returncode=0) - filter_path = _write_filter_file(tmp_path) - project = SyncProject( - name="research", path="app/data/research", local_sync_path="/tmp/research" - ) - - project_sync( - project, "my-bucket", run=runner, is_installed=lambda: True, filter_path=filter_path - ) - - cmd, _ = runner.calls[0] - assert "--progress" in cmd - assert "--verbose" not in cmd - - -def test_project_sync_no_local_path(): - project = SyncProject(name="research", path="app/data/research") - with pytest.raises(RcloneError) as exc_info: - project_sync(project, "my-bucket", is_installed=lambda: True) - assert "no local_sync_path configured" in str(exc_info.value) - - -def test_project_sync_checks_rclone_installed(): - project = SyncProject( - name="research", path="app/data/research", local_sync_path="/tmp/research" - ) - with pytest.raises(RcloneError) as exc_info: - project_sync(project, "my-bucket", is_installed=lambda: False) - assert "rclone is not installed" in str(exc_info.value) - - -def test_project_bisync_success(tmp_path): - runner = _Runner(returncode=0) - filter_path = _write_filter_file(tmp_path) - state_path = tmp_path / "state" - project = SyncProject( - name="research", path="app/data/research", local_sync_path="/tmp/research" - ) - - result = project_bisync( - project, - "my-bucket", - run=runner, - is_installed=lambda: True, - version=(1, 64, 2), - filter_path=filter_path, - state_path=state_path, - is_initialized=lambda _name: True, - ) - - assert result is True - cmd, _ = runner.calls[0] - assert cmd[:2] == ["rclone", "bisync"] - _assert_has_consistency_headers(cmd) - assert "--resilient" in cmd - assert "--conflict-resolve=newer" in cmd - assert "--max-delete=25" in cmd - assert "--compare=modtime" in cmd - assert "--workdir" in cmd - assert str(state_path) in cmd - - -def test_project_bisync_requires_resync_first_time(tmp_path): - filter_path = _write_filter_file(tmp_path) - state_path = tmp_path / "state" - project = SyncProject( - name="research", path="app/data/research", local_sync_path="/tmp/research" - ) - - with pytest.raises(RcloneError) as exc_info: - project_bisync( - project, - "my-bucket", - is_installed=lambda: True, - version=(1, 64, 2), - filter_path=filter_path, - state_path=state_path, - is_initialized=lambda _name: False, - ) - - assert "requires --resync" in str(exc_info.value) - - -def test_project_bisync_with_resync_flag(tmp_path): - runner = _Runner(returncode=0) - filter_path = _write_filter_file(tmp_path) - state_path = tmp_path / "state" - project = SyncProject( - name="research", path="app/data/research", local_sync_path="/tmp/research" - ) - - result = project_bisync( - project, - "my-bucket", - resync=True, - run=runner, - is_installed=lambda: True, - version=(1, 64, 2), - filter_path=filter_path, - state_path=state_path, - is_initialized=lambda _name: False, - ) - - assert result is True - cmd, _ = runner.calls[0] - assert "--resync" in cmd - - -def test_project_bisync_dry_run_skips_init_check(tmp_path): - runner = _Runner(returncode=0) - filter_path = _write_filter_file(tmp_path) - state_path = tmp_path / "state" - project = SyncProject( - name="research", path="app/data/research", local_sync_path="/tmp/research" - ) - - result = project_bisync( - project, - "my-bucket", - dry_run=True, - run=runner, - is_installed=lambda: True, - version=(1, 64, 2), - filter_path=filter_path, - state_path=state_path, - is_initialized=lambda _name: False, - ) - - assert result is True - cmd, _ = runner.calls[0] - assert "--dry-run" in cmd - - -def test_project_bisync_no_local_path(): - project = SyncProject(name="research", path="app/data/research") - with pytest.raises(RcloneError) as exc_info: - project_bisync(project, "my-bucket", is_installed=lambda: True) - assert "no local_sync_path configured" in str(exc_info.value) - - -def test_project_bisync_checks_rclone_installed(tmp_path): - project = SyncProject( - name="research", path="app/data/research", local_sync_path="/tmp/research" - ) - with pytest.raises(RcloneError) as exc_info: - project_bisync( - project, - "my-bucket", - is_installed=lambda: False, - filter_path=_write_filter_file(tmp_path), - state_path=tmp_path / "state", - is_initialized=lambda _name: True, - ) - assert "rclone is not installed" in str(exc_info.value) - - -def test_project_bisync_includes_empty_dirs_flag_when_supported(tmp_path): - runner = _Runner(returncode=0) - filter_path = _write_filter_file(tmp_path) - state_path = tmp_path / "state" - project = SyncProject( - name="research", path="app/data/research", local_sync_path="/tmp/research" - ) - - project_bisync( - project, - "my-bucket", - run=runner, - is_installed=lambda: True, - version=(1, 64, 2), - filter_path=filter_path, - state_path=state_path, - is_initialized=lambda _name: True, - ) - - cmd, _ = runner.calls[0] - assert "--create-empty-src-dirs" in cmd - - -def test_project_bisync_excludes_empty_dirs_flag_when_not_supported(tmp_path): - runner = _Runner(returncode=0) - filter_path = _write_filter_file(tmp_path) - state_path = tmp_path / "state" - project = SyncProject( - name="research", path="app/data/research", local_sync_path="/tmp/research" - ) - - project_bisync( - project, - "my-bucket", - run=runner, - is_installed=lambda: True, - version=(1, 60, 1), - filter_path=filter_path, - state_path=state_path, - is_initialized=lambda _name: True, - ) - - cmd, _ = runner.calls[0] - assert "--create-empty-src-dirs" not in cmd - - def test_project_check_success(tmp_path): runner = _Runner(returncode=0) filter_path = _write_filter_file(tmp_path) @@ -492,105 +190,6 @@ def test_check_rclone_installed_not_found(): assert "https://rclone.org/downloads/" in error_msg -def test_get_rclone_version_parses_standard_version(): - get_rclone_version.cache_clear() - runner = _Runner(stdout="rclone v1.64.2\n- os/version: darwin 23.0.0\n- os/arch: arm64\n") - assert get_rclone_version(run=runner) == (1, 64, 2) - - -def test_get_rclone_version_parses_dev_version(): - get_rclone_version.cache_clear() - runner = _Runner(stdout="rclone v1.60.1-DEV\n- os/version: linux 5.15.0\n") - assert get_rclone_version(run=runner) == (1, 60, 1) - - -def test_get_rclone_version_handles_invalid_output(): - get_rclone_version.cache_clear() - runner = _Runner(stdout="not a valid version string") - assert get_rclone_version(run=runner) is None - - -def test_get_rclone_version_handles_exception(): - get_rclone_version.cache_clear() - - def bad_run(_cmd, **_kwargs): - raise Exception("Command failed") - - assert get_rclone_version(run=bad_run) is None - - -def test_get_rclone_version_handles_timeout(): - get_rclone_version.cache_clear() - from subprocess import TimeoutExpired - - def bad_run(_cmd, **_kwargs): - raise TimeoutExpired(cmd="rclone version", timeout=10) - - assert get_rclone_version(run=bad_run) is None - - -def test_supports_create_empty_src_dirs_true_for_new_version(): - assert supports_create_empty_src_dirs((1, 64, 2)) is True - - -def test_supports_create_empty_src_dirs_true_for_exact_min_version(): - assert supports_create_empty_src_dirs((1, 64, 0)) is True - - -def test_supports_create_empty_src_dirs_false_for_old_version(): - assert supports_create_empty_src_dirs((1, 60, 1)) is False - - -def test_supports_create_empty_src_dirs_false_for_unknown_version(): - assert supports_create_empty_src_dirs(None) is False - - -def test_min_rclone_version_constant(): - assert MIN_RCLONE_VERSION_EMPTY_DIRS == (1, 64, 0) - - -def test_project_sync_includes_no_preallocate_flag(tmp_path): - """Sync command includes --local-no-preallocate to prevent NUL byte padding.""" - runner = _Runner(returncode=0) - filter_path = _write_filter_file(tmp_path) - project = SyncProject(name="research", path="/research", local_sync_path="/tmp/research") - - project_sync( - project, - "my-bucket", - run=runner, - is_installed=lambda: True, - filter_path=filter_path, - ) - - cmd, _ = runner.calls[0] - assert "--local-no-preallocate" in cmd - - -def test_project_bisync_includes_no_preallocate_flag(tmp_path): - """Bisync command includes --local-no-preallocate to prevent NUL byte padding.""" - runner = _Runner(returncode=0) - filter_path = _write_filter_file(tmp_path) - state_path = tmp_path / "state" - project = SyncProject( - name="research", path="app/data/research", local_sync_path="/tmp/research" - ) - - project_bisync( - project, - "my-bucket", - run=runner, - is_installed=lambda: True, - version=(1, 64, 2), - filter_path=filter_path, - state_path=state_path, - is_initialized=lambda _name: True, - ) - - cmd, _ = runner.calls[0] - assert "--local-no-preallocate" in cmd - - # --- Directional transfer primitives (push / pull, issue #858) --- @@ -919,45 +518,6 @@ def test_project_transfer_keep_cloud_on_push_preserves_cloud(tmp_path): # --- .bmignore deletion semantics (issue #1032) --- -def test_project_sync_includes_delete_excluded(tmp_path): - """The one-way mirror removes newly-ignored files from cloud (#1032). - - Without --delete-excluded, a file added to .bmignore after it synced is - invisible to rclone's deletion pass and stranded on the tenant. - """ - runner = _Runner(returncode=0) - filter_path = _write_filter_file(tmp_path) - project = SyncProject(name="research", path="/research", local_sync_path="/tmp/research") - - project_sync( - project, "my-bucket", run=runner, is_installed=lambda: True, filter_path=filter_path - ) - - cmd, _ = runner.calls[0] - assert "--delete-excluded" in cmd - - -def test_project_bisync_omits_delete_excluded(tmp_path): - """The two-way mirror must never delete based on the exclude filter.""" - runner = _Runner(returncode=0) - filter_path = _write_filter_file(tmp_path) - project = SyncProject(name="research", path="/research", local_sync_path="/tmp/research") - - project_bisync( - project, - "my-bucket", - run=runner, - is_installed=lambda: True, - version=(1, 64, 2), - filter_path=filter_path, - state_path=tmp_path / "state", - is_initialized=lambda _name: True, - ) - - cmd, _ = runner.calls[0] - assert "--delete-excluded" not in cmd - - @pytest.mark.parametrize("direction", ["push", "pull"]) def test_project_copy_omits_delete_excluded(tmp_path, direction): """push/pull are additive transfers: no filter-based deletion either.""" diff --git a/tests/test_remedy_emission_sites.py b/tests/test_remedy_emission_sites.py index 9be520f96..aa1ab386d 100644 --- a/tests/test_remedy_emission_sites.py +++ b/tests/test_remedy_emission_sites.py @@ -27,8 +27,8 @@ MODE_RESTRICTED_COMMANDS: dict[tuple[str, ...], str] = { ("bm", "project", "index"): "runs the local reindex, which rejects cloud projects", ("bm", "reindex"): "runs the local reindex, which rejects cloud projects", - ("bm", "cloud", "bisync"): "_require_personal_workspace rejects Team workspaces", - ("bm", "cloud", "sync"): "_require_personal_workspace rejects Team workspaces", + ("bm", "cloud", "bisync"): "was removed in 1.0 and only prints migration guidance", + ("bm", "cloud", "sync"): "was removed in 1.0 and only prints migration guidance", ("bm", "cloud", "prune"): "_require_personal_workspace rejects Team workspaces", } @@ -51,10 +51,6 @@ "passes index_command=None when routing is cloud, so describe() says the server " "indexes it instead of naming a local command" ), - ("cli/commands/cloud/project_sync.py", "bisync_reset"): ( - "inside `bm cloud bisync-reset`, which calls _require_personal_workspace itself; " - "the hints repeat that command's own invocation" - ), ("index/watch_service.py", "warn_unreadable_new_directories"): ( "names `bm project index` only when local_index_available, which handle_changes " "sets from the project's mode; a cloud project's watched copy gets a permissions "