Repository navigation
Description
Overview
Refactor bm tool commands to eliminate code duplication, improve testability, and validate cloud mode functionality.
Current State: The CLI tools work in both local and cloud mode (via get_client() context manager), but have significant code duplication and inconsistent patterns.
Goal: Clean, consistent, testable CLI tool commands with explicit cloud mode validation.
Problems
- Code duplication: Project resolution logic repeated 4 times across commands
- Inconsistent patterns:
recent_activityhas no project parameter while others do - Hard to test: Direct
asyncio.run()calls make testing difficult - Mixed concerns: Project resolution + tool invocation in every command
- No cloud mode tests: Only local ASGI tests exist, cloud routing unvalidated
Solution
1. Extract Shared Utilities
Create src/basic_memory/cli/commands/tool_utils.py:
def resolve_project(project: Optional[str] = None) -> str:
"""Resolve project name from parameter or default."""
config_manager = ConfigManager()
if project is not None:
project_name, _ = config_manager.get_project(project)
if not project_name:
typer.echo(f"No project found named: {project}", err=True)
raise typer.Exit(1)
return project_name
return config_manager.default_project
def run_async_tool(tool_func: Callable[..., Any], *args, **kwargs) -> Any:
"""Run an async MCP tool function with proper error handling."""
try:
return asyncio.run(tool_func(*args, **kwargs))
except Exception as e:
if not isinstance(e, typer.Exit):
typer.echo(f"Error: {e}", err=True)
raise typer.Exit(1)
raise2. Refactor Tool Commands
Before (80 lines):
@tool_app.command()
def write_note(title, content, folder, project=None, tags=None):
try:
# 10 lines of duplicated project resolution
config_manager = ConfigManager()
project_name = None
if project is not None:
project_name, _ = config_manager.get_project(project)
if not project_name:
typer.echo(f"No project found named: {project}", err=True)
raise typer.Exit(1)
project_name = project_name or config_manager.default_project
note = asyncio.run(mcp_write_note.fn(title, content, folder, project_name, tags))
rprint(note)
except Exception as e:
if not isinstance(e, typer.Exit):
typer.echo(f"Error during write_note: {e}", err=True)
raise typer.Exit(1)
raiseAfter (20 lines):
@tool_app.command()
def write_note(title, content, folder, project=None, tags=None):
project_name = resolve_project(project)
result = run_async_tool(mcp_write_note.fn, title, content, folder, project_name, tags)
rprint(result)3. Add Cloud Mode Tests
Create tests/cli/test_cli_tools_cloud.py to validate:
- Tools route to
/proxyendpoint in cloud mode - Auth tokens properly injected
- Error handling when not authenticated
Benefits
✅ 50% code reduction: ~400 lines → ~200 lines
✅ Consistency: All tools use same pattern
✅ Testability: Easier to test with extracted utilities
✅ Maintainability: Single place to update project resolution
✅ Cloud validation: Tests verify cloud routing works
Implementation Tasks
-
Create
src/basic_memory/cli/commands/tool_utils.py- Add
resolve_project()helper - Add
run_async_tool()helper - Add unit tests for utilities
- Add
-
Refactor
src/basic_memory/cli/commands/tool.pycommands-
write_note→ use helpers -
read_note→ use helpers -
build_context→ use helpers -
search_notes→ use helpers, fix search_type logic -
recent_activity→ add project param, use helpers -
continue_conversation→ use run_async_tool helper
-
-
Add cloud mode tests
- Create
tests/cli/test_cli_tools_cloud.py - Test tools route to
/proxyin cloud mode - Test auth token injection
- Test error handling when not authenticated
- Create
-
Update documentation
- Update CLAUDE.md with new pattern
- Add examples showing local vs cloud usage
Breaking Changes
None! This is a pure refactor:
- Same CLI interface
- Same behavior in local/cloud modes
- Backwards compatible
Files to Change
src/basic_memory/cli/commands/tool_utils.py(NEW)src/basic_memory/cli/commands/tool.py(REFACTOR)tests/cli/test_cli_tools.py(UPDATE - add utils tests)tests/cli/test_cli_tools_cloud.py(NEW)
Related
- Builds on SPEC-16 Phase 0 async client refactor (refactor: async client context manager pattern for cloud consolidation #344)
- Validates cloud mode functionality before Phase 1 deployment
Activity
claude commentedon Oct 10, 2025
Claude finished @phernandez's task —— View job •
claude/issue-346-20251010-1703• Create PR ➔Implementation Complete ✅
Issue Classification:
Task List:
src/basic_memory/cli/commands/tool_utils.pywith helperstests/cli/test_cli_tools_cloud.py)Implementation Summary:
✅ Created
tool_utils.pywith two helper functions:resolve_project()- Centralized project resolution logicrun_async_tool()- Standardized async execution with error handling✅ Refactored all 6 CLI commands to use new helpers:
write_note- 99→47 lines (52% reduction)read_note- 33→5 lines (85% reduction)build_context- 42→13 lines (69% reduction)recent_activity- 20→11 lines (45% reduction) + added project parametersearch_notes- 70→28 lines (60% reduction) + fixed bugcontinue_conversation- 18→3 lines (83% reduction)Total Impact:
search_notesrecent_activityFiles Changed:
src/basic_memory/cli/commands/tool_utils.py(NEW - 62 lines)src/basic_memory/cli/commands/tool.py(REFACTORED - 169 deletions, 107 insertions)tests/cli/test_cli_tools.py(UPDATED - added 6 utility tests)tests/cli/test_cli_tools_cloud.py(NEW - 168 lines)Bug Fix Details:
The
search_notescommand had a critical bug where search_type logic was creating tuples and overwriting values:--- |
refactor: extract CLI tool utilities and add cloud mode tests