mirror of
https://github.com/basicmachines-co/basic-memory
synced 2026-06-21 13:47:35 +00:00
Compare commits
33 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2c29dcc2b2 | |||
| 448210e552 | |||
| 3621bb7b4d | |||
| f80ac0ee72 | |||
| 23ddf1918c | |||
| 2aca19aa05 | |||
| 827f7cf3e3 | |||
| bd4f55158b | |||
| 5360005122 | |||
| 39f811f8b5 | |||
| 8e69c8b533 | |||
| 627a5c3c22 | |||
| cd88945b22 | |||
| cd8e372f0a | |||
| a589f8b894 | |||
| c2f4b632cf | |||
| 46d102cef1 | |||
| 8e4dc026ce | |||
| 7af8e198c2 | |||
| 12b51522bc | |||
| ac9e148bcc | |||
| 546e3cd8db | |||
| de4737cc22 | |||
| 77eefeb252 | |||
| e5923a0378 | |||
| 1bf348259b | |||
| 224e4bf9e4 | |||
| 9f1db23c78 | |||
| db5ef7d35c | |||
| f50650763d | |||
| 8a065c32f4 | |||
| 2a3adc109a | |||
| a52ce1c860 |
@@ -1,190 +0,0 @@
|
||||
# /project:check-health - Project Health Assessment
|
||||
|
||||
Comprehensive health check of the Basic Memory project including code quality, test coverage, dependencies, and documentation.
|
||||
|
||||
## Usage
|
||||
```
|
||||
/project:check-health
|
||||
```
|
||||
|
||||
## Implementation
|
||||
|
||||
You are an expert DevOps engineer for the Basic Memory project. When the user runs `/project:check-health`, execute the following comprehensive assessment:
|
||||
|
||||
### Step 1: Git Repository Health
|
||||
1. **Repository Status**
|
||||
```bash
|
||||
git status
|
||||
git log --oneline -5
|
||||
git branch -vv
|
||||
```
|
||||
- Check working directory status
|
||||
- Verify branch alignment with remote
|
||||
- Check recent commit activity
|
||||
|
||||
2. **Branch Analysis**
|
||||
- Verify on main branch
|
||||
- Check if ahead/behind remote
|
||||
- Identify any untracked files
|
||||
|
||||
### Step 2: Code Quality Assessment
|
||||
1. **Linting and Formatting**
|
||||
```bash
|
||||
uv run ruff check .
|
||||
uv run pyright
|
||||
```
|
||||
- Count linting issues by severity
|
||||
- Check type annotation coverage
|
||||
- Verify code formatting compliance
|
||||
|
||||
2. **Test Suite Health**
|
||||
```bash
|
||||
uv run pytest --collect-only -q
|
||||
uv run pytest --co -q | wc -l
|
||||
```
|
||||
- Count total tests
|
||||
- Check for test discovery issues
|
||||
- Verify test structure integrity
|
||||
|
||||
### Step 3: Dependency Analysis
|
||||
1. **Dependency Health**
|
||||
```bash
|
||||
uv tree
|
||||
uv lock --dry-run
|
||||
```
|
||||
- Check for dependency conflicts
|
||||
- Identify outdated dependencies
|
||||
- Verify lock file consistency
|
||||
|
||||
2. **Security Scan**
|
||||
```bash
|
||||
uv run pip-audit --desc
|
||||
```
|
||||
- Scan for known vulnerabilities
|
||||
- Check dependency licenses
|
||||
- Identify security advisories
|
||||
|
||||
### Step 4: Performance Metrics
|
||||
1. **Test Performance**
|
||||
```bash
|
||||
uv run pytest --durations=10
|
||||
```
|
||||
- Identify slowest tests
|
||||
- Check overall test execution time
|
||||
- Monitor test suite growth
|
||||
|
||||
2. **Build Performance**
|
||||
```bash
|
||||
time uv run python -c "import basic_memory"
|
||||
```
|
||||
- Check import time
|
||||
- Validate package installation
|
||||
- Monitor startup performance
|
||||
|
||||
### Step 5: Documentation Health
|
||||
1. **Documentation Coverage**
|
||||
- Check README.md currency
|
||||
- Verify CLI documentation
|
||||
- Validate MCP tool documentation
|
||||
- Check changelog completeness
|
||||
|
||||
2. **API Documentation**
|
||||
- Verify docstring coverage
|
||||
- Check type annotation completeness
|
||||
- Validate example code
|
||||
|
||||
### Step 6: Project Metrics
|
||||
1. **Code Statistics**
|
||||
```bash
|
||||
find src -name "*.py" | xargs wc -l
|
||||
find tests -name "*.py" | xargs wc -l
|
||||
```
|
||||
- Lines of code trends
|
||||
- Test-to-code ratio
|
||||
- File organization metrics
|
||||
|
||||
## Health Report Format
|
||||
|
||||
Generate comprehensive health dashboard:
|
||||
|
||||
```
|
||||
🏥 Basic Memory Project Health Report
|
||||
|
||||
📊 OVERALL HEALTH: 🟢 EXCELLENT (92/100)
|
||||
|
||||
🗂️ GIT REPOSITORY
|
||||
✅ Clean working directory
|
||||
✅ Up to date with origin/main
|
||||
✅ Recent commit activity (5 commits this week)
|
||||
|
||||
🔍 CODE QUALITY
|
||||
✅ Linting: 0 errors, 2 warnings
|
||||
✅ Type checking: 100% coverage
|
||||
✅ Formatting: Compliant
|
||||
⚠️ Complex functions: 3 need refactoring
|
||||
|
||||
🧪 TEST SUITE
|
||||
✅ Total tests: 744
|
||||
✅ Test discovery: All tests found
|
||||
✅ Coverage: 98.2%
|
||||
⚡ Performance: 45.2s (good)
|
||||
|
||||
📦 DEPENDENCIES
|
||||
✅ Dependencies: Up to date
|
||||
✅ Security: No vulnerabilities
|
||||
✅ Conflicts: None detected
|
||||
⚠️ Outdated: 2 minor updates available
|
||||
|
||||
📖 DOCUMENTATION
|
||||
✅ README: Current
|
||||
✅ API docs: 95% coverage
|
||||
⚠️ CLI reference: Needs update
|
||||
✅ Changelog: Complete
|
||||
|
||||
📈 METRICS
|
||||
├── Source code: 15,432 lines
|
||||
├── Test code: 8,967 lines
|
||||
├── Test ratio: 58% (excellent)
|
||||
└── Complexity: Low (maintainable)
|
||||
|
||||
🎯 RECOMMENDATIONS:
|
||||
1. Update CLI documentation
|
||||
2. Refactor 3 complex functions
|
||||
3. Update minor dependencies
|
||||
4. Consider splitting large test files
|
||||
|
||||
🏆 PROJECT STATUS: Ready for v0.13.0 release!
|
||||
```
|
||||
|
||||
## Health Scoring
|
||||
|
||||
### Excellent (90-100)
|
||||
- All quality gates pass
|
||||
- High test coverage (>95%)
|
||||
- No security issues
|
||||
- Documentation current
|
||||
|
||||
### Good (75-89)
|
||||
- Minor issues present
|
||||
- Good test coverage (>90%)
|
||||
- No critical security issues
|
||||
- Most documentation current
|
||||
|
||||
### Needs Attention (60-74)
|
||||
- Several quality issues
|
||||
- Adequate test coverage (>80%)
|
||||
- Minor security concerns
|
||||
- Documentation gaps
|
||||
|
||||
### Critical (<60)
|
||||
- Major quality problems
|
||||
- Low test coverage (<80%)
|
||||
- Security vulnerabilities
|
||||
- Significant documentation issues
|
||||
|
||||
## Context
|
||||
- Provides comprehensive project overview
|
||||
- Identifies potential issues before they become problems
|
||||
- Tracks project health trends over time
|
||||
- Helps prioritize maintenance tasks
|
||||
- Supports release readiness decisions
|
||||
@@ -1,62 +0,0 @@
|
||||
# Basic Memory Custom Commands
|
||||
|
||||
This directory contains custom Claude Code slash commands for the Basic Memory project.
|
||||
|
||||
## Available Commands
|
||||
|
||||
### Release Management (`/project:release:*`)
|
||||
- `/project:release:beta` - Create beta releases with automated quality checks
|
||||
- `/project:release:release` - Create stable releases with comprehensive validation
|
||||
- `/project:release:release-check` - Pre-flight validation without making changes
|
||||
- `/project:release:changelog` - Generate changelog entries from commits
|
||||
|
||||
### Development (`/project:*`)
|
||||
- `/project:test-coverage` - Run tests with detailed coverage analysis
|
||||
- `/project:test-live` - Live testing suite using real Basic Memory installation
|
||||
- `/project:lint-fix` - Run comprehensive linting with auto-fix
|
||||
- `/project:check-health` - Comprehensive project health assessment
|
||||
|
||||
## Command Structure
|
||||
|
||||
Commands are organized by functionality:
|
||||
```
|
||||
.claude/commands/
|
||||
├── release/ # Release management commands
|
||||
│ ├── beta.md # /project:release:beta
|
||||
│ ├── release.md # /project:release:release
|
||||
│ ├── release-check.md # /project:release:release-check
|
||||
│ └── changelog.md # /project:release:changelog
|
||||
├── test-coverage.md # /project:test-coverage
|
||||
├── test-live.md # /project:test-live
|
||||
├── lint-fix.md # /project:lint-fix
|
||||
├── check-health.md # /project:check-health
|
||||
└── commands.md # This overview file
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Commands are invoked using the `/project:` prefix:
|
||||
- `/project:release:beta v0.13.0b4`
|
||||
- `/project:test-coverage mcp`
|
||||
- `/project:test-live core`
|
||||
- `/project:release:release-check`
|
||||
- `/project:check-health`
|
||||
|
||||
## Implementation
|
||||
|
||||
Each command is implemented as a Markdown file containing structured prompts that:
|
||||
1. Validate preconditions
|
||||
2. Execute steps in the correct order
|
||||
3. Handle errors gracefully
|
||||
4. Provide clear status updates
|
||||
5. Return actionable results
|
||||
|
||||
## Tooling Integration
|
||||
|
||||
Commands leverage existing project tooling:
|
||||
- `just check` - Quality checks
|
||||
- `just test` - Test suite
|
||||
- `just update-deps` - Dependency updates
|
||||
- `uv` - Package management
|
||||
- `git` - Version control
|
||||
- GitHub Actions - CI/CD pipeline
|
||||
@@ -1,145 +0,0 @@
|
||||
# /project:lint-fix - Comprehensive Code Quality Fix
|
||||
|
||||
Run comprehensive linting and auto-fix code quality issues across the codebase.
|
||||
|
||||
## Usage
|
||||
```
|
||||
/project:lint-fix
|
||||
```
|
||||
|
||||
## Implementation
|
||||
|
||||
You are an expert code quality engineer for the Basic Memory project. When the user runs `/project:lint-fix`, execute the following steps:
|
||||
|
||||
### Step 1: Pre-flight Check
|
||||
1. **Verify Clean Working Directory**
|
||||
```bash
|
||||
git status --porcelain
|
||||
```
|
||||
- Check for uncommitted changes
|
||||
- Warn if working directory is not clean
|
||||
- Suggest stashing changes if needed
|
||||
|
||||
### Step 2: Import Organization
|
||||
1. **Fix Import Order and Cleanup**
|
||||
```bash
|
||||
uv run ruff check --select I --fix .
|
||||
```
|
||||
- Sort imports by category (standard, third-party, local)
|
||||
- Remove unused imports
|
||||
- Fix import spacing and organization
|
||||
|
||||
### Step 3: Code Formatting
|
||||
1. **Apply Consistent Formatting**
|
||||
```bash
|
||||
uv run ruff format .
|
||||
```
|
||||
- Format code according to project style
|
||||
- Fix line length issues (100 chars max)
|
||||
- Standardize quotes and spacing
|
||||
|
||||
### Step 4: Linting with Auto-fix
|
||||
1. **Fix Linting Issues**
|
||||
```bash
|
||||
uv run ruff check --fix .
|
||||
```
|
||||
- Auto-fix safe linting issues
|
||||
- Report any remaining manual fixes needed
|
||||
- Focus on code quality and best practices
|
||||
|
||||
### Step 5: Type Checking
|
||||
1. **Validate Type Annotations**
|
||||
```bash
|
||||
uv run pyright
|
||||
```
|
||||
- Check for type errors
|
||||
- Report any missing type annotations
|
||||
- Validate type compatibility
|
||||
|
||||
### Step 6: Report Generation
|
||||
Generate comprehensive quality report:
|
||||
|
||||
```
|
||||
🔧 Code Quality Fix Report
|
||||
|
||||
✅ FIXES APPLIED:
|
||||
├── Import organization: 12 files updated
|
||||
├── Code formatting: 8 files reformatted
|
||||
├── Auto-fixable lint issues: 23 issues resolved
|
||||
└── Total files processed: 156
|
||||
|
||||
⚠️ MANUAL ATTENTION NEEDED:
|
||||
├── Type annotations missing in entity_service.py:45
|
||||
├── Complex function needs refactoring in sync_service.py:123
|
||||
└── Unused variable in test_utils.py:67
|
||||
|
||||
🎯 QUALITY SCORE: 96.2% (excellent)
|
||||
|
||||
📁 Run `git diff` to review all changes
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Common Issues
|
||||
- **Merge Conflicts**: Provide resolution guidance
|
||||
- **Syntax Errors**: Point to specific files and lines
|
||||
- **Type Errors**: Suggest specific fixes
|
||||
- **Import Errors**: Check for missing dependencies
|
||||
|
||||
### Recovery Steps
|
||||
- If auto-fixes introduce issues, provide rollback instructions
|
||||
- If type checking fails, suggest incremental fixes
|
||||
- If tests break, provide debugging guidance
|
||||
|
||||
## Quality Gates
|
||||
|
||||
### Must Pass
|
||||
- [ ] All auto-fixable lint issues resolved
|
||||
- [ ] Code formatting consistent
|
||||
- [ ] No syntax errors
|
||||
- [ ] Import organization clean
|
||||
|
||||
### Should Pass (Warnings)
|
||||
- [ ] No type checking errors
|
||||
- [ ] No complex function warnings
|
||||
- [ ] No unused variables/imports
|
||||
- [ ] Consistent naming conventions
|
||||
|
||||
## Output Examples
|
||||
|
||||
### Successful Fix
|
||||
```
|
||||
🎉 CODE QUALITY IMPROVED!
|
||||
|
||||
✅ All auto-fixes applied successfully
|
||||
📏 Code formatting: 100% compliant
|
||||
🔍 Linting: No issues found
|
||||
🏷️ Type checking: All passed
|
||||
|
||||
Ready for commit! Use:
|
||||
git add -A && git commit -m "style: fix code quality issues"
|
||||
```
|
||||
|
||||
### Issues Requiring Attention
|
||||
```
|
||||
⚠️ PARTIAL SUCCESS - MANUAL FIXES NEEDED
|
||||
|
||||
✅ Auto-fixes applied: 45 issues
|
||||
❌ Manual fixes needed: 3 issues
|
||||
|
||||
Priority fixes:
|
||||
1. Fix type annotation in services/entity_service.py:142
|
||||
2. Simplify complex function in sync/sync_service.py:67
|
||||
3. Remove unused import in tests/conftest.py:12
|
||||
|
||||
Run these commands:
|
||||
# Fix specific file
|
||||
uv run pyright src/basic_memory/services/entity_service.py
|
||||
```
|
||||
|
||||
## Context
|
||||
- Uses ruff for fast Python linting and formatting
|
||||
- Uses pyright for type checking
|
||||
- Follows project code style guidelines (100 char line length)
|
||||
- Maintains backward compatibility
|
||||
- Integrates with existing pre-commit hooks
|
||||
@@ -8,7 +8,7 @@ Analyze commits and generate formatted changelog entry for a version.
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `version` (required): Version like `v0.13.0` or `v0.13.0b4`
|
||||
- `version` (required): Version like `v0.14.0` or `v0.14.0b1`
|
||||
- `type` (optional): `beta`, `rc`, or `stable` (default: `stable`)
|
||||
|
||||
## Implementation
|
||||
@@ -59,8 +59,9 @@ You are an expert technical writer for the Basic Memory project. When the user r
|
||||
### Step 3: Generate Changelog Entry
|
||||
Create formatted entry following existing CHANGELOG.md style:
|
||||
|
||||
Example:
|
||||
```markdown
|
||||
## v0.13.0 (2025-06-03)
|
||||
## <version> (<date>)
|
||||
|
||||
### Features
|
||||
|
||||
@@ -128,6 +129,8 @@ Create formatted entry following existing CHANGELOG.md style:
|
||||
## Output Format
|
||||
|
||||
### For Beta Releases
|
||||
|
||||
Example:
|
||||
```markdown
|
||||
## v0.13.0b4 (2025-06-03)
|
||||
|
||||
|
||||
@@ -1,131 +0,0 @@
|
||||
# /test-coverage - Run Tests with Coverage Analysis
|
||||
|
||||
Execute test suite with comprehensive coverage reporting and analysis.
|
||||
|
||||
## Usage
|
||||
```
|
||||
/test-coverage [pattern]
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `pattern` (optional): Test pattern to run specific tests (e.g., `test_mcp`, `*integration*`)
|
||||
|
||||
## Implementation
|
||||
|
||||
You are an expert QA engineer for the Basic Memory project. When the user runs `/test-coverage`, execute the following steps:
|
||||
|
||||
### Step 1: Test Execution
|
||||
1. **Run Tests with Coverage**
|
||||
```bash
|
||||
# Full test suite
|
||||
uv run pytest --cov=basic_memory --cov-report=html --cov-report=term -v
|
||||
|
||||
# Or with pattern if provided
|
||||
uv run pytest tests/*{pattern}* --cov=basic_memory --cov-report=html --cov-report=term -v
|
||||
```
|
||||
|
||||
2. **Generate Coverage Reports**
|
||||
- Terminal summary with percentages
|
||||
- HTML report for detailed analysis
|
||||
- Identify files below coverage threshold
|
||||
|
||||
### Step 2: Coverage Analysis
|
||||
1. **Summary Statistics**
|
||||
- Overall coverage percentage
|
||||
- Number of files with 100% coverage
|
||||
- Files below 95% threshold
|
||||
- Total lines covered/missed
|
||||
|
||||
2. **Detailed Breakdown**
|
||||
- Coverage by module/package
|
||||
- Identify untested code paths
|
||||
- Find missing edge case tests
|
||||
|
||||
### Step 3: Report Generation
|
||||
Generate comprehensive coverage report:
|
||||
|
||||
```
|
||||
🧪 Test Coverage Report
|
||||
|
||||
📊 OVERALL COVERAGE: 98.2% (target: 95%+)
|
||||
|
||||
✅ EXCELLENT COVERAGE (>95%):
|
||||
├── basic_memory/mcp/: 99.1%
|
||||
├── basic_memory/services/: 98.8%
|
||||
├── basic_memory/repository/: 97.9%
|
||||
└── basic_memory/api/: 96.2%
|
||||
|
||||
⚠️ NEEDS ATTENTION (<95%):
|
||||
├── basic_memory/sync/: 94.1% (missing 12 lines)
|
||||
└── basic_memory/importers/: 91.8% (missing 23 lines)
|
||||
|
||||
🎯 SPECIFIC GAPS:
|
||||
├── sync_service.py:142-145 (error handling)
|
||||
├── importer_base.py:67-70 (edge case)
|
||||
└── file_utils.py:89 (exception path)
|
||||
|
||||
📁 HTML Report: htmlcov/index.html
|
||||
🚀 Run `open htmlcov/index.html` to view detailed report
|
||||
```
|
||||
|
||||
### Step 4: Actionable Recommendations
|
||||
1. **Coverage Improvements**
|
||||
- Suggest specific tests to add
|
||||
- Identify edge cases to cover
|
||||
- Recommend integration tests
|
||||
|
||||
2. **Quality Insights**
|
||||
- Highlight well-tested modules
|
||||
- Point out testing patterns to follow
|
||||
- Suggest refactoring for testability
|
||||
|
||||
## Advanced Analysis
|
||||
|
||||
### Performance Metrics
|
||||
- Test execution time by module
|
||||
- Slowest tests identification
|
||||
- Coverage collection overhead
|
||||
|
||||
### Integration Coverage
|
||||
- MCP tool integration tests
|
||||
- API endpoint coverage
|
||||
- Database operation coverage
|
||||
- File system operation coverage
|
||||
|
||||
## Output Examples
|
||||
|
||||
### Full Coverage Success
|
||||
```
|
||||
🎉 EXCELLENT COVERAGE!
|
||||
|
||||
📊 Coverage: 98.7% (744 tests passed)
|
||||
✅ All modules above 95% threshold
|
||||
🏆 23 files with 100% coverage
|
||||
⚡ Tests completed in 45.2s
|
||||
|
||||
Ready for release! 🚀
|
||||
```
|
||||
|
||||
### Coverage Issues Found
|
||||
```
|
||||
⚠️ COVERAGE GAPS DETECTED
|
||||
|
||||
📊 Coverage: 92.1% (below 95% target)
|
||||
❌ 3 modules need attention
|
||||
🔍 43 uncovered lines found
|
||||
|
||||
Priority fixes:
|
||||
1. Add tests for error handling in sync_service.py
|
||||
2. Cover edge cases in importer_base.py
|
||||
3. Test exception paths in file_utils.py
|
||||
|
||||
Run specific tests:
|
||||
uv run pytest tests/sync/ -v
|
||||
```
|
||||
|
||||
## Context
|
||||
- Uses pytest with coverage plugin
|
||||
- Generates both terminal and HTML reports
|
||||
- Focuses on actionable improvement suggestions
|
||||
- Integrates with existing test infrastructure
|
||||
- Helps maintain high code quality standards
|
||||
+265
-80
@@ -1,6 +1,7 @@
|
||||
# /project:test-live - Live Basic Memory Testing Suite
|
||||
|
||||
Execute comprehensive real-world testing of Basic Memory using the installed version, following the methodology in TESTING.md. All test results are recorded as notes in a dedicated test project.
|
||||
Execute comprehensive real-world testing of Basic Memory using the installed version.
|
||||
All test results are recorded as notes in a dedicated test project.
|
||||
|
||||
## Usage
|
||||
```
|
||||
@@ -8,12 +9,45 @@ Execute comprehensive real-world testing of Basic Memory using the installed ver
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `phase` (optional): Specific test phase to run (`core`, `features`, `edge`, `workflows`, `stress`, or `all`)
|
||||
- `phase` (optional): Specific test phase to run (`recent`, `core`, `features`, `edge`, `workflows`, `stress`, or `all`)
|
||||
- `recent` - Focus on recent changes and new features (recommended for regular testing)
|
||||
- `core` - Essential tools only (Tier 1: write_note, read_note, search_notes, edit_note, list_projects, switch_project)
|
||||
- `features` - Core + important workflows (Tier 1 + Tier 2)
|
||||
- `all` - Comprehensive testing of all tools and scenarios
|
||||
|
||||
## Implementation
|
||||
|
||||
You are an expert QA engineer conducting live testing of Basic Memory.
|
||||
When the user runs `/project:test-live`, execute comprehensive testing following the TESTING.md methodology:
|
||||
When the user runs `/project:test-live`, execute comprehensive test plan:
|
||||
|
||||
## Tool Testing Priority
|
||||
|
||||
### **Tier 1: Critical Core (Always Test)**
|
||||
1. **write_note** - Foundation of all knowledge creation
|
||||
2. **read_note** - Primary knowledge retrieval mechanism
|
||||
3. **search_notes** - Essential for finding information
|
||||
4. **edit_note** - Core content modification capability
|
||||
5. **list_memory_projects** - Project discovery and status
|
||||
6. **switch_project** - Context switching for multi-project workflows
|
||||
|
||||
### **Tier 2: Important Workflows (Usually Test)**
|
||||
7. **recent_activity** - Understanding what's changed
|
||||
8. **build_context** - Conversation continuity via memory:// URLs
|
||||
9. **create_memory_project** - Essential for project setup
|
||||
10. **move_note** - Knowledge organization
|
||||
11. **sync_status** - Understanding system state
|
||||
|
||||
### **Tier 3: Enhanced Functionality (Sometimes Test)**
|
||||
12. **view_note** - Claude Desktop artifact display
|
||||
13. **read_content** - Raw content access
|
||||
14. **delete_note** - Content removal
|
||||
15. **list_directory** - File system exploration
|
||||
16. **set_default_project** - Configuration
|
||||
17. **delete_project** - Administrative cleanup
|
||||
|
||||
### **Tier 4: Specialized (Rarely Test)**
|
||||
18. **canvas** - Obsidian visualization (specialized use case)
|
||||
19. **MCP Prompts** - Enhanced UX tools (ai_assistant_guide, continue_conversation)
|
||||
|
||||
### Pre-Test Setup
|
||||
|
||||
@@ -22,7 +56,13 @@ When the user runs `/project:test-live`, execute comprehensive testing following
|
||||
- Check version and confirm it's the expected release
|
||||
- Test MCP connection and tool availability
|
||||
|
||||
2. **Test Project Creation**
|
||||
2. **Recent Changes Analysis** (if phase includes 'recent' or 'all')
|
||||
- Run `git log --oneline -20` to examine recent commits
|
||||
- Identify new features, bug fixes, and enhancements
|
||||
- Generate targeted test scenarios for recent changes
|
||||
- Prioritize regression testing for recently fixed issues
|
||||
|
||||
3. **Test Project Creation**
|
||||
|
||||
Run the bash `date` command to get the current date/time.
|
||||
|
||||
@@ -34,83 +74,158 @@ Run the bash `date` command to get the current date/time.
|
||||
|
||||
Make sure to switch to the newly created project with the `switch_project()` tool.
|
||||
|
||||
3. **Baseline Documentation**
|
||||
4. **Baseline Documentation**
|
||||
Create initial test session note with:
|
||||
- Test environment details
|
||||
- Version being tested
|
||||
- Recent changes identified (if applicable)
|
||||
- Test objectives and scope
|
||||
- Start timestamp
|
||||
|
||||
### Phase 1: Core Functionality Validation
|
||||
### Phase 0: Recent Changes Validation (if 'recent' or 'all' phase)
|
||||
|
||||
Test all fundamental MCP tools systematically:
|
||||
Based on recent commit analysis, create targeted test scenarios:
|
||||
|
||||
**write_note Tests:**
|
||||
- Basic note creation with various content types
|
||||
- Frontmatter handling (tags, custom fields)
|
||||
- Special characters in titles and content
|
||||
- Unicode and emoji support
|
||||
- Empty notes and minimal content
|
||||
**Recent Changes Test Protocol:**
|
||||
1. **Feature Addition Tests** - For each new feature identified:
|
||||
- Test basic functionality
|
||||
- Test integration with existing tools
|
||||
- Verify documentation accuracy
|
||||
- Test edge cases and error handling
|
||||
|
||||
**read_note Tests:**
|
||||
- Read by title, permalink, memory:// URLs
|
||||
- Non-existent notes (error handling)
|
||||
- Notes with complex formatting
|
||||
- Performance with large notes
|
||||
2. **Bug Fix Regression Tests** - For each recent fix:
|
||||
- Recreate the original problem scenario
|
||||
- Verify the fix works as expected
|
||||
- Test related functionality isn't broken
|
||||
- Document the verification in test notes
|
||||
|
||||
**view_note Tests:**
|
||||
- View notes as formatted artifacts (Claude Desktop)
|
||||
- Title extraction from frontmatter and headings
|
||||
- Unicode and emoji content in artifacts
|
||||
- Error handling for non-existent notes
|
||||
- Artifact display quality and readability
|
||||
3. **Performance/Enhancement Validation** - For optimizations:
|
||||
- Establish baseline timing
|
||||
- Compare with expected improvements
|
||||
- Test under various load conditions
|
||||
- Document performance observations
|
||||
|
||||
**search_notes Tests:**
|
||||
- Simple text queries
|
||||
- Tag-based searches
|
||||
- Boolean operators and complex queries
|
||||
- Empty/no results scenarios
|
||||
- Performance with growing knowledge base
|
||||
**Example Recent Changes (Update based on actual git log):**
|
||||
- Watch Service Restart (#156): Test project creation → file modification → automatic restart
|
||||
- Cross-Project Moves (#161): Test move_note with cross-project detection
|
||||
- Docker Environment Support (#174): Test BASIC_MEMORY_HOME behavior
|
||||
- MCP Server Logging (#164): Verify log level configurations
|
||||
|
||||
**Recent Activity Tests:**
|
||||
- Various timeframes ("today", "1 week", "1d")
|
||||
- Type filtering (if available)
|
||||
- Empty project scenarios
|
||||
- Performance with many recent changes
|
||||
### Phase 1: Core Functionality Validation (Tier 1 Tools)
|
||||
|
||||
**Context Building Tests:**
|
||||
- Different depth levels (1, 2, 3+)
|
||||
- Various timeframes
|
||||
- Relation traversal accuracy
|
||||
- Performance with complex graphs
|
||||
Test essential MCP tools that form the foundation of Basic Memory:
|
||||
|
||||
### Phase 2: v0.13.0 Feature Deep Dive
|
||||
**1. write_note Tests (Critical):**
|
||||
- ✅ Basic note creation with frontmatter
|
||||
- ✅ Special characters and Unicode in titles
|
||||
- ✅ Various content types (lists, headings, code blocks)
|
||||
- ✅ Empty notes and minimal content edge cases
|
||||
- ⚠️ Error handling for invalid parameters
|
||||
|
||||
**Project Management:**
|
||||
- Create multiple projects dynamically
|
||||
- Switch between projects mid-conversation
|
||||
- Cross-project operations
|
||||
- Project discovery and status
|
||||
- Default project behavior
|
||||
- Invalid project handling
|
||||
**2. read_note Tests (Critical):**
|
||||
- ✅ Read by title, permalink, memory:// URLs
|
||||
- ✅ Non-existent notes (error handling)
|
||||
- ✅ Notes with complex markdown formatting
|
||||
- ⚠️ Performance with large notes (>10MB)
|
||||
|
||||
**Advanced Note Editing:**
|
||||
- `edit_note` with append operations
|
||||
- Prepend operations
|
||||
- Find/replace with validation
|
||||
- Section replacement under headers
|
||||
- Error scenarios (invalid operations)
|
||||
- Frontmatter preservation
|
||||
**3. search_notes Tests (Critical):**
|
||||
- ✅ Simple text queries across content
|
||||
- ✅ Tag-based searches with multiple tags
|
||||
- ✅ Boolean operators (AND, OR, NOT)
|
||||
- ✅ Empty/no results scenarios
|
||||
- ⚠️ Performance with 100+ notes
|
||||
|
||||
**File Management:**
|
||||
- `move_note` within same project
|
||||
- Move between projects
|
||||
- Automatic folder creation
|
||||
- Special characters in paths
|
||||
- Database consistency validation
|
||||
- Search index updates after moves
|
||||
**4. edit_note Tests (Critical):**
|
||||
- ✅ Append operations preserving frontmatter
|
||||
- ✅ Prepend operations
|
||||
- ✅ Find/replace with validation
|
||||
- ✅ Section replacement under headers
|
||||
- ⚠️ Error scenarios (invalid operations)
|
||||
|
||||
### Phase 3: Edge Case Exploration
|
||||
**5. list_memory_projects Tests (Critical):**
|
||||
- ✅ Display all projects with status indicators
|
||||
- ✅ Current and default project identification
|
||||
- ✅ Empty project list handling
|
||||
- ✅ Project metadata accuracy
|
||||
|
||||
**6. switch_project Tests (Critical):**
|
||||
- ✅ Switch between existing projects
|
||||
- ✅ Context preservation during switch
|
||||
- ⚠️ Invalid project name handling
|
||||
- ✅ Confirmation of successful switch
|
||||
|
||||
### Phase 2: Important Workflows (Tier 2 Tools)
|
||||
|
||||
**7. recent_activity Tests (Important):**
|
||||
- ✅ Various timeframes ("today", "1 week", "1d")
|
||||
- ✅ Type filtering capabilities
|
||||
- ✅ Empty project scenarios
|
||||
- ⚠️ Performance with many recent changes
|
||||
|
||||
**8. build_context Tests (Important):**
|
||||
- ✅ Different depth levels (1, 2, 3+)
|
||||
- ✅ Various timeframes for context
|
||||
- ✅ memory:// URL navigation
|
||||
- ⚠️ Performance with complex relation graphs
|
||||
|
||||
**9. create_memory_project Tests (Important):**
|
||||
- ✅ Create projects dynamically
|
||||
- ✅ Set default during creation
|
||||
- ✅ Path validation and creation
|
||||
- ⚠️ Invalid paths and names
|
||||
- ✅ Integration with existing projects
|
||||
|
||||
**10. move_note Tests (Important):**
|
||||
- ✅ Move within same project
|
||||
- ✅ Cross-project moves with detection (#161)
|
||||
- ✅ Automatic folder creation
|
||||
- ✅ Database consistency validation
|
||||
- ⚠️ Special characters in paths
|
||||
|
||||
**11. sync_status Tests (Important):**
|
||||
- ✅ Background operation monitoring
|
||||
- ✅ File synchronization status
|
||||
- ✅ Project sync state reporting
|
||||
- ⚠️ Error state handling
|
||||
|
||||
### Phase 3: Enhanced Functionality (Tier 3 Tools)
|
||||
|
||||
**12. view_note Tests (Enhanced):**
|
||||
- ✅ Claude Desktop artifact display
|
||||
- ✅ Title extraction from frontmatter
|
||||
- ✅ Unicode and emoji content rendering
|
||||
- ⚠️ Error handling for non-existent notes
|
||||
|
||||
**13. read_content Tests (Enhanced):**
|
||||
- ✅ Raw file content access
|
||||
- ✅ Binary file handling
|
||||
- ✅ Image file reading
|
||||
- ⚠️ Large file performance
|
||||
|
||||
**14. delete_note Tests (Enhanced):**
|
||||
- ✅ Single note deletion
|
||||
- ✅ Database consistency after deletion
|
||||
- ⚠️ Non-existent note handling
|
||||
- ✅ Confirmation of successful deletion
|
||||
|
||||
**15. list_directory Tests (Enhanced):**
|
||||
- ✅ Directory content listing
|
||||
- ✅ Depth control and filtering
|
||||
- ✅ File name globbing
|
||||
- ⚠️ Empty directory handling
|
||||
|
||||
**16. set_default_project Tests (Enhanced):**
|
||||
- ✅ Change default project
|
||||
- ✅ Configuration persistence
|
||||
- ⚠️ Invalid project handling
|
||||
|
||||
**17. delete_project Tests (Enhanced):**
|
||||
- ✅ Project removal from config
|
||||
- ✅ Database cleanup
|
||||
- ⚠️ Default project protection
|
||||
- ⚠️ Non-existent project handling
|
||||
|
||||
### Phase 4: Edge Case Exploration
|
||||
|
||||
**Boundary Testing:**
|
||||
- Very long titles and content (stress limits)
|
||||
@@ -134,7 +249,7 @@ Test all fundamental MCP tools systematically:
|
||||
- Rapid successive operations
|
||||
- Memory usage monitoring
|
||||
|
||||
### Phase 4: Real-World Workflow Scenarios
|
||||
### Phase 5: Real-World Workflow Scenarios
|
||||
|
||||
**Meeting Notes Pipeline:**
|
||||
1. Create meeting notes with action items
|
||||
@@ -164,7 +279,35 @@ Test all fundamental MCP tools systematically:
|
||||
4. Update content with edit operations
|
||||
5. Validate knowledge graph integrity
|
||||
|
||||
### Phase 5: Creative Stress Testing
|
||||
### Phase 6: Specialized Tools Testing (Tier 4)
|
||||
|
||||
**18. canvas Tests (Specialized):**
|
||||
- ✅ JSON Canvas generation
|
||||
- ✅ Node and edge creation
|
||||
- ✅ Obsidian compatibility
|
||||
- ⚠️ Complex graph handling
|
||||
|
||||
**19. MCP Prompts Tests (Specialized):**
|
||||
- ✅ ai_assistant_guide output
|
||||
- ✅ continue_conversation functionality
|
||||
- ✅ Formatted search results
|
||||
- ✅ Enhanced activity reports
|
||||
|
||||
### Phase 7: Integration & File Watching Tests
|
||||
|
||||
**File System Integration:**
|
||||
- ✅ Watch service behavior with file changes
|
||||
- ✅ Project creation → watch restart (#156)
|
||||
- ✅ Multi-project synchronization
|
||||
- ⚠️ MCP→API→DB→File stack validation
|
||||
|
||||
**Real Integration Testing:**
|
||||
- ✅ End-to-end file watching vs manual operations
|
||||
- ✅ Cross-session persistence
|
||||
- ✅ Database consistency across operations
|
||||
- ⚠️ Performance under real file system changes
|
||||
|
||||
### Phase 8: Creative Stress Testing
|
||||
|
||||
**Creative Exploration:**
|
||||
- Rapid project creation/switching patterns
|
||||
@@ -180,6 +323,26 @@ Test all fundamental MCP tools systematically:
|
||||
- Complex boolean search expressions
|
||||
- Resource constraint testing
|
||||
|
||||
## Test Execution Guidelines
|
||||
|
||||
### Quick Testing (core/features phases)
|
||||
- Focus on Tier 1 tools (core) or Tier 1+2 (features)
|
||||
- Test essential functionality and common edge cases
|
||||
- Record critical issues immediately
|
||||
- Complete in 15-20 minutes
|
||||
|
||||
### Comprehensive Testing (all phase)
|
||||
- Cover all tiers systematically
|
||||
- Include specialized tools and stress testing
|
||||
- Document performance baselines
|
||||
- Complete in 45-60 minutes
|
||||
|
||||
### Recent Changes Focus (recent phase)
|
||||
- Analyze git log for recent commits
|
||||
- Generate targeted test scenarios
|
||||
- Focus on regression testing for fixes
|
||||
- Validate new features thoroughly
|
||||
|
||||
## Test Observation Format
|
||||
|
||||
Record ALL observations immediately as Basic Memory notes:
|
||||
@@ -202,14 +365,14 @@ permalink: test-session-[phase]-[timestamp]
|
||||
## Test Results
|
||||
|
||||
### ✅ Successful Operations
|
||||
- [timestamp] write_note: Created note with emoji title 📝 #functionality
|
||||
- [timestamp] search_notes: Boolean query returned 23 results in 0.4s #performance
|
||||
- [timestamp] edit_note: Append operation preserved frontmatter #reliability
|
||||
- [timestamp] ✅ write_note: Created note with emoji title 📝 #tier1 #functionality
|
||||
- [timestamp] ✅ search_notes: Boolean query returned 23 results in 0.4s #tier1 #performance
|
||||
- [timestamp] ✅ edit_note: Append operation preserved frontmatter #tier1 #reliability
|
||||
|
||||
### ⚠️ Issues Discovered
|
||||
- [timestamp] move_note: Slow with deep folder paths (2.1s) #performance
|
||||
- [timestamp] search_notes: Unicode query returned unexpected results #bug
|
||||
- [timestamp] project switch: Context lost for memory:// URLs #issue
|
||||
- [timestamp] ⚠️ move_note: Slow with deep folder paths (2.1s) #tier2 #performance
|
||||
- [timestamp] 🚨 search_notes: Unicode query returned unexpected results #tier1 #bug #critical
|
||||
- [timestamp] ⚠️ build_context: Context lost for memory:// URLs #tier2 #issue
|
||||
|
||||
### 🚀 Enhancements Identified
|
||||
- edit_note could benefit from preview mode #ux-improvement
|
||||
@@ -353,24 +516,44 @@ For each error discovered:
|
||||
- Create comprehensive summary report
|
||||
- Generate development recommendations
|
||||
|
||||
## Testing Success Criteria
|
||||
|
||||
### Core Testing (Tier 1) - Must Pass
|
||||
- All 6 critical tools function correctly
|
||||
- No critical bugs in essential workflows
|
||||
- Acceptable performance for basic operations
|
||||
- Error handling works as expected
|
||||
|
||||
### Feature Testing (Tier 1+2) - Should Pass
|
||||
- All 11 core + important tools function
|
||||
- Workflow scenarios complete successfully
|
||||
- Performance meets baseline expectations
|
||||
- Integration points work correctly
|
||||
|
||||
### Comprehensive Testing (All Tiers) - Complete Coverage
|
||||
- All tools tested across all scenarios
|
||||
- Edge cases and stress testing completed
|
||||
- Performance baselines established
|
||||
- Full documentation of issues and enhancements
|
||||
|
||||
## Expected Outcomes
|
||||
|
||||
**System Validation:**
|
||||
- v0.13.0 feature verification in real usage
|
||||
- Edge case discovery beyond unit tests
|
||||
- Feature verification prioritized by tier importance
|
||||
- Recent changes validated for regression
|
||||
- Performance baseline establishment
|
||||
- Bug identification with reproduction cases
|
||||
- Bug identification with severity assessment
|
||||
|
||||
**Knowledge Base Creation:**
|
||||
- Comprehensive testing documentation
|
||||
- Prioritized testing documentation
|
||||
- Real usage examples for user guides
|
||||
- Edge case scenarios for future testing
|
||||
- Recent changes validation records
|
||||
- Performance insights for optimization
|
||||
|
||||
**Development Insights:**
|
||||
- Prioritized bug fix list
|
||||
- Tier-based bug priority list
|
||||
- Recent changes impact assessment
|
||||
- Enhancement ideas from real usage
|
||||
- Architecture validation results
|
||||
- User experience improvement areas
|
||||
|
||||
## Post-Test Deliverables
|
||||
@@ -402,9 +585,11 @@ For each error discovered:
|
||||
- Add performance benchmarks and targets
|
||||
|
||||
## Context
|
||||
- Uses installed basic-memory version (not development)
|
||||
- Uses real installed basic-memory version
|
||||
- Tests complete MCP→API→DB→File stack
|
||||
- Creates living documentation in Basic Memory itself
|
||||
- Follows integration over isolation philosophy
|
||||
- Prioritizes testing by tool importance and usage frequency
|
||||
- Adapts to recent development changes dynamically
|
||||
- Focuses on real usage patterns over checklist validation
|
||||
- Generates actionable insights for development team
|
||||
- Generates actionable insights prioritized by impact
|
||||
@@ -111,4 +111,4 @@ jobs:
|
||||
uses: anthropics/claude-code-action@beta
|
||||
with:
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
allowed_tools: Bash(uv run pytest),Bash(uv run ruff check . --fix),Bash(uv run ruff format .),Bash(uv run pyright),Bash(just test),Bash(just lint),Bash(just format),Bash(just type-check),Bash(just check),Read,Write,Edit,MultiEdit,Glob,Grep,LS
|
||||
allowed_tools: Bash(uv run pytest),Bash(uv run ruff check . --fix),Bash(uv run ruff format .),Bash(uv run pyright),Bash(just test),Bash(just lint),Bash(just format),Bash(just type-check),Bash(just check),Read,Write,Edit,MultiEdit,Glob,Grep,LS, mcp__web_search
|
||||
@@ -57,6 +57,8 @@ jobs:
|
||||
name: Update Homebrew Formula
|
||||
needs: release
|
||||
runs-on: ubuntu-latest
|
||||
# Only run for stable releases (not dev, beta, or rc versions)
|
||||
if: ${{ !contains(github.ref_name, 'dev') && !contains(github.ref_name, 'b') && !contains(github.ref_name, 'rc') }}
|
||||
permissions:
|
||||
contents: write
|
||||
actions: read
|
||||
@@ -80,3 +82,4 @@ jobs:
|
||||
env:
|
||||
# Personal Access Token with repo scope for homebrew-basic-memory repo
|
||||
COMMITTER_TOKEN: ${{ secrets.HOMEBREW_TOKEN }}
|
||||
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"basic-memory": {
|
||||
"command": "uv",
|
||||
"args": [
|
||||
"--directory",
|
||||
"/Users/phernandez/dev/basicmachines/basic-memory",
|
||||
"run",
|
||||
"src/basic_memory/cli/main.py",
|
||||
"mcp"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
+168
-40
@@ -1,56 +1,184 @@
|
||||
# CHANGELOG
|
||||
|
||||
## v0.13.8 (2025-06-20)
|
||||
|
||||
### Features
|
||||
|
||||
- **Docker Container Support** - Complete Docker integration with volume mounting for Obsidian directories
|
||||
([`3269a2f`](https://github.com/basicmachines-co/basic-memory/commit/3269a2f33a7595f6d9e5207924062e2542f46759))
|
||||
- Docker Compose configuration for easy deployment
|
||||
- Volume mounting for persistent data and Obsidian integration
|
||||
- Comprehensive Docker documentation and setup guides
|
||||
- Streamlined container-based workflow
|
||||
## v0.14.2 (2025-07-03)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- **#151**: Fix reset command project configuration persistence issue
|
||||
([`af44941`](https://github.com/basicmachines-co/basic-memory/commit/af44941d5aa57b5ad7fcc6af4ed700f49bdb6d4d))
|
||||
- Reset command now properly clears project configuration from `~/.basic-memory/config.json`
|
||||
- Eliminates issue where projects would be recreated after database reset
|
||||
- Ensures clean slate when resetting Basic Memory installation
|
||||
- **#204**: Fix MCP Error with MCP-Hub integration
|
||||
([`3621bb7`](https://github.com/basicmachines-co/basic-memory/commit/3621bb7b4d6ac12d892b18e36bb8f7c9101c7b10))
|
||||
- Resolve compatibility issues with MCP-Hub
|
||||
- Improve error handling in project management tools
|
||||
- Ensure stable MCP tool integration across different environments
|
||||
|
||||
- **#148**: Resolve project state inconsistency between MCP and CLI
|
||||
([`35e4f73`](https://github.com/basicmachines-co/basic-memory/commit/35e4f73ae8a65501da4d48258ed702f957184c92))
|
||||
- Fix "Project not found" errors when switching default projects
|
||||
- MCP session now automatically refreshes when project configuration changes
|
||||
- Eliminates need to restart MCP server after project operations
|
||||
- Ensures consistent project state across CLI and MCP interfaces
|
||||
- **Modernize datetime handling and suppress SQLAlchemy warnings**
|
||||
([`f80ac0e`](https://github.com/basicmachines-co/basic-memory/commit/f80ac0e3e74b7a737a7fc7b956b5c1d61b0c67b8))
|
||||
- Replace deprecated `datetime.utcnow()` with timezone-aware alternatives
|
||||
- Suppress SQLAlchemy deprecation warnings for cleaner output
|
||||
- Improve future compatibility with Python datetime best practices
|
||||
|
||||
- **FastMCP Compatibility** - Resolve deprecation warnings for FastMCP integration
|
||||
([`7be001c`](https://github.com/basicmachines-co/basic-memory/commit/7be001ca6834b3344bb6160cbe537b36bcbaa579))
|
||||
- Update FastMCP usage patterns to eliminate deprecation warnings
|
||||
- Improve future compatibility with FastMCP library updates
|
||||
- Clean up entity repository and service layer code
|
||||
## v0.14.1 (2025-07-03)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- **#203**: Constrain fastmcp version to prevent breaking changes
|
||||
([`827f7cf`](https://github.com/basicmachines-co/basic-memory/commit/827f7cf86e7b84c56e7a43bb83f2e5d84a1ad8b8))
|
||||
- Pin fastmcp to compatible version range to avoid API breaking changes
|
||||
- Ensure stable MCP server functionality across updates
|
||||
- Improve dependency management for production deployments
|
||||
|
||||
- **#190**: Fix Problems with MCP integration
|
||||
([`bd4f551`](https://github.com/basicmachines-co/basic-memory/commit/bd4f551a5bb0b7b4d3a5b04de70e08987c6ab2f9))
|
||||
- Resolve MCP server initialization and communication issues
|
||||
- Improve error handling and recovery in MCP operations
|
||||
- Enhance stability for AI assistant integrations
|
||||
|
||||
### Features
|
||||
|
||||
- **Add Cursor IDE integration button** - One-click setup for Cursor IDE users
|
||||
([`5360005`](https://github.com/basicmachines-co/basic-memory/commit/536000512294d66090bf87abc8014f4dfc284310))
|
||||
- Direct installation button for Cursor IDE in README
|
||||
- Streamlined setup process for Cursor users
|
||||
- Enhanced developer experience for AI-powered coding
|
||||
|
||||
- **Add Homebrew installation instructions** - Official Homebrew tap support
|
||||
([`39f811f`](https://github.com/basicmachines-co/basic-memory/commit/39f811f8b57dd998445ae43537cd492c680b2e11))
|
||||
- Official Homebrew formula in basicmachines-co/basic-memory tap
|
||||
- Simplified installation process for macOS users
|
||||
- Package manager integration for easier dependency management
|
||||
|
||||
## v0.14.0 (2025-06-26)
|
||||
|
||||
### Features
|
||||
|
||||
- **Docker Container Registry Migration** - Switch from Docker Hub to GitHub Container Registry for better security and integration
|
||||
([`616c1f0`](https://github.com/basicmachines-co/basic-memory/commit/616c1f0710da59c7098a5f4843d4f017877ff7b2))
|
||||
- Automated Docker image publishing via GitHub Actions CI/CD pipeline
|
||||
- Enhanced container security with GitHub's integrated vulnerability scanning
|
||||
- Streamlined container deployment workflow for production environments
|
||||
|
||||
- **Enhanced Search Documentation** - Comprehensive search syntax examples for improved user experience
|
||||
([`a589f8b`](https://github.com/basicmachines-co/basic-memory/commit/a589f8b894e78cce01eb25656856cfea8785fbbf))
|
||||
- Detailed examples for Boolean search operators (AND, OR, NOT)
|
||||
- Advanced search patterns including phrase matching and field-specific queries
|
||||
- User-friendly documentation for complex search scenarios
|
||||
|
||||
- **Cross-Project File Management** - Intelligent move operations with project boundary detection
|
||||
([`db5ef7d`](https://github.com/basicmachines-co/basic-memory/commit/db5ef7d35cc0894309c7a57b5741c9dd978526d4))
|
||||
- Automatic detection of cross-project move attempts with helpful guidance
|
||||
- Clear error messages when attempting unsupported cross-project operations
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- **#184**: Preserve permalinks when editing notes without frontmatter permalinks
|
||||
([`c2f4b63`](https://github.com/basicmachines-co/basic-memory/commit/c2f4b632cf04921b1a3c2f0d43831b80c519cb31))
|
||||
- Fix permalink preservation during note editing operations
|
||||
- Ensure consistent permalink handling across different note formats
|
||||
- Maintain note identity and searchability during incremental edits
|
||||
|
||||
- **#183**: Implement project-specific sync status checks for MCP tools
|
||||
([`12b5152`](https://github.com/basicmachines-co/basic-memory/commit/12b51522bc953fca117fc5bc01fcb29c6ca7e13c))
|
||||
- Fix sync status reporting to correctly reflect current project state
|
||||
- Resolve inconsistencies where sync status showed global instead of project-specific information
|
||||
- Improve project isolation for sync operations and status reporting
|
||||
|
||||
- **#180**: Handle Boolean search syntax with hyphenated terms
|
||||
([`546e3cd`](https://github.com/basicmachines-co/basic-memory/commit/546e3cd8db98b74f746749d41887f8a213cd0b11))
|
||||
- Fix search parsing issues with hyphenated terms in Boolean queries
|
||||
- Improve search query tokenization for complex term structures
|
||||
- Enhanced search reliability for technical documentation and multi-word concepts
|
||||
|
||||
- **#174**: Respect BASIC_MEMORY_HOME environment variable in Docker containers
|
||||
([`9f1db23`](https://github.com/basicmachines-co/basic-memory/commit/9f1db23c78d4648e2c242ad1ee27eed85e3f3b5d))
|
||||
- Fix Docker container configuration to properly honor custom home directory settings
|
||||
- Improve containerized deployment flexibility with environment variable support
|
||||
- Ensure consistent behavior between local and containerized installations
|
||||
|
||||
- **#168**: Scope entity queries by project_id in upsert_entity method
|
||||
([`2a3adc1`](https://github.com/basicmachines-co/basic-memory/commit/2a3adc109a3e4d7ccd65cae4abf63d9bb2338326))
|
||||
- Fix entity isolation issues in multi-project setups
|
||||
- Prevent cross-project entity conflicts during database operations
|
||||
- Strengthen project boundary enforcement at the database level
|
||||
|
||||
- **#166**: Handle None from_entity in Context API RelationSummary
|
||||
([`8a065c3`](https://github.com/basicmachines-co/basic-memory/commit/8a065c32f4e41613207d29aafc952a56e3a52241))
|
||||
- Fix null pointer exceptions in relation processing
|
||||
- Improve error handling for incomplete relation data
|
||||
- Enhanced stability for knowledge graph traversal operations
|
||||
|
||||
- **#164**: Remove log level configuration from mcp_server.run()
|
||||
([`224e4bf`](https://github.com/basicmachines-co/basic-memory/commit/224e4bf9e4438c44a82ffc21bd1a282fe9087690))
|
||||
- Simplify MCP server startup by removing redundant log level settings
|
||||
- Fix potential logging configuration conflicts
|
||||
- Streamline server initialization process
|
||||
|
||||
- **#162**: Ensure permalinks are generated for entities with null permalinks during move operations
|
||||
([`f506507`](https://github.com/basicmachines-co/basic-memory/commit/f50650763dbd4322c132e4bdc959ce4bf074374b))
|
||||
- Fix move operations for entities without existing permalinks
|
||||
- Automatic permalink generation during file move operations
|
||||
- Maintain database consistency during file reorganization
|
||||
|
||||
### Technical Improvements
|
||||
|
||||
- **Comprehensive Integration Testing** - New test suites for critical user workflows
|
||||
- Full integration tests for database reset functionality
|
||||
- End-to-end project state synchronization testing
|
||||
- Real MCP client-server communication validation
|
||||
- Direct config file validation without complex mocking
|
||||
- **Comprehensive Test Coverage** - Extensive test suites for new features and edge cases
|
||||
- Enhanced test coverage for project-specific sync status functionality
|
||||
- Additional test scenarios for search syntax validation and edge cases
|
||||
- Integration tests for Docker CI workflow and container publishing
|
||||
- Comprehensive move operations testing with project boundary validation
|
||||
|
||||
- **Code Quality** - Enhanced error handling and validation
|
||||
- Improved project state management across system components
|
||||
- Better session refresh patterns for configuration changes
|
||||
- Streamlined Docker setup with reduced image size
|
||||
- **Docker CI/CD Pipeline** - Production-ready automated container publishing
|
||||
([`74847cc`](https://github.com/basicmachines-co/basic-memory/commit/74847cc3807b0c6ed511e0d83e0d560e9f07ec44))
|
||||
- Automated Docker image building and publishing on release
|
||||
- Multi-architecture container support for AMD64 and ARM64 platforms
|
||||
- Integrated security scanning and vulnerability assessments
|
||||
- Streamlined deployment pipeline for production environments
|
||||
|
||||
### Documentation
|
||||
- **Release Process Improvements** - Enhanced automation and quality gates
|
||||
([`a52ce1c`](https://github.com/basicmachines-co/basic-memory/commit/a52ce1c8605ec2cd450d1f909154172cbc30faa2))
|
||||
- Homebrew formula updates limited to stable releases only
|
||||
- Improved release automation with better quality control
|
||||
- Enhanced CI/CD pipeline reliability and error handling
|
||||
|
||||
- **Docker Integration Guide** - Complete documentation for container deployment
|
||||
- Step-by-step Docker Compose setup instructions
|
||||
- Volume mounting configuration for Obsidian workflows
|
||||
- Container-based development environment setup
|
||||
- **Code Quality Enhancements** - Improved error handling and validation
|
||||
- Better null safety in entity and relation processing
|
||||
- Enhanced project isolation validation throughout the codebase
|
||||
- Improved error messages and user guidance for edge cases
|
||||
- Strengthened database consistency guarantees across operations
|
||||
|
||||
### Infrastructure
|
||||
|
||||
- **GitHub Container Registry Integration** - Modern container infrastructure
|
||||
- Migration from Docker Hub to GitHub Container Registry (ghcr.io)
|
||||
- Improved security with integrated vulnerability scanning
|
||||
- Better integration with GitHub-based development workflow
|
||||
- Enhanced container versioning and artifact management
|
||||
|
||||
- **Enhanced CI/CD Workflows** - Robust automated testing and deployment
|
||||
- Automated Docker image publishing on releases
|
||||
- Comprehensive test coverage validation before deployment
|
||||
- Multi-platform container building and publishing
|
||||
- Integration with GitHub's security and monitoring tools
|
||||
|
||||
### Migration Guide
|
||||
|
||||
This release includes several behind-the-scenes improvements and fixes. All changes are backward compatible:
|
||||
|
||||
- **Docker Users**: Container images now served from `ghcr.io/basicmachines-co/basic-memory` instead of Docker Hub
|
||||
- **Search Users**: Enhanced search syntax handling - existing queries continue to work unchanged
|
||||
- **Multi-Project Users**: Improved project isolation - all existing projects remain fully functional
|
||||
- **All Users**: Enhanced stability and error handling - no breaking changes to existing workflows
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# Latest stable release
|
||||
uv tool install basic-memory
|
||||
|
||||
# Update existing installation
|
||||
uv tool upgrade basic-memory
|
||||
|
||||
# Docker (new registry)
|
||||
docker pull ghcr.io/basicmachines-co/basic-memory:latest
|
||||
```
|
||||
|
||||
## v0.13.7 (2025-06-19)
|
||||
|
||||
|
||||
@@ -236,7 +236,9 @@ Basic Memory uses `uv-dynamic-versioning` for automatic version management based
|
||||
- Create version tag: `git tag v0.13.0 && git push origin v0.13.0`
|
||||
|
||||
#### Homebrew Formula Updates
|
||||
- Automatically triggered after successful PyPI release
|
||||
- Automatically triggered after successful PyPI release for **stable releases only**
|
||||
- **Stable releases** (e.g., v0.13.7) automatically update the main `basic-memory` formula
|
||||
- **Pre-releases** (dev/beta/rc) are NOT automatically updated - users must specify version manually
|
||||
- Updates formula in `basicmachines-co/homebrew-basic-memory` repo
|
||||
- Requires `HOMEBREW_TOKEN` secret in GitHub repository settings:
|
||||
- Create a fine-grained Personal Access Token with `Contents: Read and Write` and `Actions: Read` scopes on `basicmachines-co/homebrew-basic-memory`
|
||||
|
||||
@@ -33,6 +33,10 @@ https://github.com/user-attachments/assets/a55d8238-8dd0-454a-be4c-8860dbbd0ddc
|
||||
# Install with uv (recommended)
|
||||
uv tool install basic-memory
|
||||
|
||||
# or with Homebrew
|
||||
brew tap basicmachines-co/basic-memory
|
||||
brew install basic-memory
|
||||
|
||||
# Configure Claude Desktop (edit ~/Library/Application Support/Claude/claude_desktop_config.json)
|
||||
# Add this to your config:
|
||||
{
|
||||
@@ -66,6 +70,13 @@ npx -y @smithery/cli install @basicmachines-co/basic-memory --client claude
|
||||
|
||||
This installs and configures Basic Memory without requiring manual edits to the Claude Desktop configuration file. Note: The Smithery installation uses their hosted MCP server, while your data remains stored locally as Markdown files.
|
||||
|
||||
### Add to Cursor
|
||||
|
||||
Once you have installed Basic Memory revisit this page for the 1-click installer for Cursor:
|
||||
|
||||
[](https://cursor.com/install-mcp?name=basic-memory&config=eyJjb21tYW5kIjoiL1VzZXJzL2RyZXcvLmxvY2FsL2Jpbi91dnggYmFzaWMtbWVtb3J5IG1jcCJ9)
|
||||
|
||||
|
||||
### Glama.ai
|
||||
|
||||
<a href="https://glama.ai/mcp/servers/o90kttu9ym">
|
||||
@@ -214,7 +225,7 @@ title: <Entity title>
|
||||
type: <The type of Entity> (e.g. note)
|
||||
permalink: <a uri slug>
|
||||
|
||||
- <optional metadata> (such as tags)
|
||||
- <optional metadata> (such as tags)
|
||||
```
|
||||
|
||||
### Observations
|
||||
|
||||
@@ -17,7 +17,7 @@ test: test-unit test-int
|
||||
|
||||
# Lint and fix code
|
||||
lint:
|
||||
ruff check . --fix
|
||||
uv run ruff check . --fix
|
||||
|
||||
# Type check code
|
||||
type-check:
|
||||
|
||||
+2
-2
@@ -30,7 +30,7 @@ dependencies = [
|
||||
"alembic>=1.14.1",
|
||||
"pillow>=11.1.0",
|
||||
"pybars3>=0.9.7",
|
||||
"fastmcp>=2.3.4",
|
||||
"fastmcp>=2.3.4,<2.10.0",
|
||||
"pyjwt>=2.10.1",
|
||||
"python-dotenv>=1.1.0",
|
||||
"pytest-aio>=1.9.0",
|
||||
@@ -123,4 +123,4 @@ omit = [
|
||||
]
|
||||
|
||||
[tool.logfire]
|
||||
ignore_no_config = true
|
||||
ignore_no_config = true
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""basic-memory - Local-first knowledge management combining Zettelkasten with knowledge graphs"""
|
||||
|
||||
# Package version - updated by release automation
|
||||
__version__ = "0.13.7"
|
||||
__version__ = "0.14.2"
|
||||
|
||||
# API version for FastAPI - independent of package version
|
||||
__api_version__ = "v0"
|
||||
|
||||
@@ -52,7 +52,7 @@ async def to_graph_context(
|
||||
file_path=item.file_path,
|
||||
permalink=item.permalink, # pyright: ignore
|
||||
relation_type=item.relation_type, # pyright: ignore
|
||||
from_entity=from_entity.title, # pyright: ignore
|
||||
from_entity=from_entity.title if from_entity else None,
|
||||
to_entity=to_entity.title if to_entity else None,
|
||||
created_at=item.created_at,
|
||||
)
|
||||
|
||||
@@ -78,7 +78,6 @@ def mcp(
|
||||
if transport == "stdio":
|
||||
mcp_server.run(
|
||||
transport=transport,
|
||||
log_level="INFO",
|
||||
)
|
||||
elif transport == "streamable-http" or transport == "sse":
|
||||
mcp_server.run(
|
||||
|
||||
@@ -45,7 +45,9 @@ class BasicMemoryConfig(BaseSettings):
|
||||
env: Environment = Field(default="dev", description="Environment name")
|
||||
|
||||
projects: Dict[str, str] = Field(
|
||||
default_factory=lambda: {"main": str(Path.home() / "basic-memory")},
|
||||
default_factory=lambda: {
|
||||
"main": str(Path(os.getenv("BASIC_MEMORY_HOME", Path.home() / "basic-memory")))
|
||||
},
|
||||
description="Mapping of project names to their filesystem paths",
|
||||
)
|
||||
default_project: str = Field(
|
||||
@@ -92,7 +94,9 @@ class BasicMemoryConfig(BaseSettings):
|
||||
"""Ensure configuration is valid after initialization."""
|
||||
# Ensure main project exists
|
||||
if "main" not in self.projects: # pragma: no cover
|
||||
self.projects["main"] = str(Path.home() / "basic-memory")
|
||||
self.projects["main"] = str(
|
||||
Path(os.getenv("BASIC_MEMORY_HOME", Path.home() / "basic-memory"))
|
||||
)
|
||||
|
||||
# Ensure default project is valid
|
||||
if self.default_project not in self.projects: # pragma: no cover
|
||||
|
||||
@@ -38,7 +38,9 @@ def entity_model_from_markdown(
|
||||
# Update basic fields
|
||||
model.title = markdown.frontmatter.title
|
||||
model.entity_type = markdown.frontmatter.type
|
||||
model.permalink = markdown.frontmatter.permalink
|
||||
# Only update permalink if it exists in frontmatter, otherwise preserve existing
|
||||
if markdown.frontmatter.permalink is not None:
|
||||
model.permalink = markdown.frontmatter.permalink
|
||||
model.file_path = str(file_path)
|
||||
model.content_type = "text/markdown"
|
||||
model.created_at = markdown.created
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""OAuth authentication provider for Basic Memory MCP server."""
|
||||
|
||||
import secrets
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Dict, Optional
|
||||
|
||||
import jwt
|
||||
@@ -92,7 +92,7 @@ class BasicMemoryOAuthProvider(
|
||||
self.authorization_codes[auth_code] = BasicMemoryAuthorizationCode(
|
||||
code=auth_code,
|
||||
scopes=params.scopes or [],
|
||||
expires_at=(datetime.utcnow() + timedelta(minutes=10)).timestamp(),
|
||||
expires_at=(datetime.now(timezone.utc) + timedelta(minutes=10)).timestamp(),
|
||||
client_id=client.client_id,
|
||||
code_challenge=params.code_challenge,
|
||||
redirect_uri=params.redirect_uri,
|
||||
@@ -119,7 +119,7 @@ class BasicMemoryOAuthProvider(
|
||||
|
||||
if code and code.client_id == client.client_id:
|
||||
# Check if expired
|
||||
if datetime.utcnow().timestamp() > code.expires_at:
|
||||
if datetime.now(timezone.utc).timestamp() > code.expires_at:
|
||||
del self.authorization_codes[authorization_code]
|
||||
return None
|
||||
return code
|
||||
@@ -135,7 +135,7 @@ class BasicMemoryOAuthProvider(
|
||||
refresh_token = secrets.token_urlsafe(32)
|
||||
|
||||
# Store tokens
|
||||
expires_at = (datetime.utcnow() + timedelta(hours=1)).timestamp()
|
||||
expires_at = (datetime.now(timezone.utc) + timedelta(hours=1)).timestamp()
|
||||
|
||||
self.access_tokens[access_token] = BasicMemoryAccessToken(
|
||||
token=access_token,
|
||||
@@ -187,7 +187,7 @@ class BasicMemoryOAuthProvider(
|
||||
new_refresh_token = secrets.token_urlsafe(32)
|
||||
|
||||
# Store new tokens
|
||||
expires_at = (datetime.utcnow() + timedelta(hours=1)).timestamp()
|
||||
expires_at = (datetime.now(timezone.utc) + timedelta(hours=1)).timestamp()
|
||||
|
||||
self.access_tokens[new_access_token] = BasicMemoryAccessToken(
|
||||
token=new_access_token,
|
||||
@@ -220,7 +220,7 @@ class BasicMemoryOAuthProvider(
|
||||
|
||||
if access_token:
|
||||
# Check if expired
|
||||
if access_token.expires_at and datetime.utcnow().timestamp() > access_token.expires_at:
|
||||
if access_token.expires_at and datetime.now(timezone.utc).timestamp() > access_token.expires_at:
|
||||
logger.debug("Token found in memory but expired, removing")
|
||||
del self.access_tokens[token]
|
||||
return None
|
||||
@@ -262,8 +262,8 @@ class BasicMemoryOAuthProvider(
|
||||
"iss": self.issuer_url,
|
||||
"sub": client_id,
|
||||
"aud": "basic-memory",
|
||||
"exp": datetime.utcnow() + timedelta(hours=1),
|
||||
"iat": datetime.utcnow(),
|
||||
"exp": datetime.now(timezone.utc) + timedelta(hours=1),
|
||||
"iat": datetime.now(timezone.utc),
|
||||
"scopes": scopes,
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import os
|
||||
import secrets
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
import httpx
|
||||
@@ -123,7 +123,7 @@ class SupabaseOAuthProvider(
|
||||
self.pending_auth_codes[state] = SupabaseAuthorizationCode(
|
||||
code=state,
|
||||
scopes=params.scopes or [],
|
||||
expires_at=(datetime.utcnow() + timedelta(minutes=10)).timestamp(),
|
||||
expires_at=(datetime.now(timezone.utc) + timedelta(minutes=10)).timestamp(),
|
||||
client_id=client.client_id,
|
||||
code_challenge=params.code_challenge,
|
||||
redirect_uri=params.redirect_uri,
|
||||
@@ -218,7 +218,7 @@ class SupabaseOAuthProvider(
|
||||
|
||||
if code and code.client_id == client.client_id:
|
||||
# Check expiration
|
||||
if datetime.utcnow().timestamp() > code.expires_at:
|
||||
if datetime.now(timezone.utc).timestamp() > code.expires_at:
|
||||
del self.pending_auth_codes[authorization_code]
|
||||
return None
|
||||
return code
|
||||
@@ -453,8 +453,8 @@ class SupabaseOAuthProvider(
|
||||
"email": email,
|
||||
"scopes": scopes,
|
||||
"supabase_token": supabase_access_token[:10] + "...", # Reference only
|
||||
"exp": datetime.utcnow() + timedelta(hours=1),
|
||||
"iat": datetime.utcnow(),
|
||||
"exp": datetime.now(timezone.utc) + timedelta(hours=1),
|
||||
"iat": datetime.now(timezone.utc),
|
||||
}
|
||||
|
||||
# Use Supabase JWT secret if available
|
||||
|
||||
@@ -20,24 +20,24 @@ from basic_memory.mcp.tools.edit_note import edit_note
|
||||
from basic_memory.mcp.tools.move_note import move_note
|
||||
from basic_memory.mcp.tools.sync_status import sync_status
|
||||
from basic_memory.mcp.tools.project_management import (
|
||||
list_projects,
|
||||
list_memory_projects,
|
||||
switch_project,
|
||||
get_current_project,
|
||||
set_default_project,
|
||||
create_project,
|
||||
create_memory_project,
|
||||
delete_project,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"build_context",
|
||||
"canvas",
|
||||
"create_project",
|
||||
"create_memory_project",
|
||||
"delete_note",
|
||||
"delete_project",
|
||||
"edit_note",
|
||||
"get_current_project",
|
||||
"list_directory",
|
||||
"list_projects",
|
||||
"list_memory_projects",
|
||||
"move_note",
|
||||
"read_content",
|
||||
"read_note",
|
||||
|
||||
@@ -82,10 +82,15 @@ async def build_context(
|
||||
logger.info(f"Building context from {url}")
|
||||
# URL is already validated and normalized by MemoryUrl type annotation
|
||||
|
||||
# Get the active project first to check project-specific sync status
|
||||
active_project = get_active_project(project)
|
||||
|
||||
# Check migration status and wait briefly if needed
|
||||
from basic_memory.mcp.tools.utils import wait_for_migration_or_return_status
|
||||
|
||||
migration_status = await wait_for_migration_or_return_status(timeout=5.0)
|
||||
migration_status = await wait_for_migration_or_return_status(
|
||||
timeout=5.0, project_name=active_project.name
|
||||
)
|
||||
if migration_status: # pragma: no cover
|
||||
# Return a proper GraphContext with status message
|
||||
from basic_memory.schemas.memory import MemoryMetadata
|
||||
@@ -102,8 +107,6 @@ async def build_context(
|
||||
uri=migration_status, # Include status in metadata
|
||||
),
|
||||
)
|
||||
|
||||
active_project = get_active_project(project)
|
||||
project_url = active_project.project_url
|
||||
|
||||
response = await call_get(
|
||||
|
||||
@@ -7,9 +7,155 @@ from loguru import logger
|
||||
|
||||
from basic_memory.mcp.async_client import client
|
||||
from basic_memory.mcp.server import mcp
|
||||
from basic_memory.mcp.tools.utils import call_post
|
||||
from basic_memory.mcp.tools.utils import call_post, call_get
|
||||
from basic_memory.mcp.project_session import get_active_project
|
||||
from basic_memory.schemas import EntityResponse
|
||||
from basic_memory.schemas.project_info import ProjectList
|
||||
|
||||
|
||||
async def _detect_cross_project_move_attempt(
|
||||
identifier: str, destination_path: str, current_project: str
|
||||
) -> Optional[str]:
|
||||
"""Detect potential cross-project move attempts and return guidance.
|
||||
|
||||
Args:
|
||||
identifier: The note identifier being moved
|
||||
destination_path: The destination path
|
||||
current_project: The current active project
|
||||
|
||||
Returns:
|
||||
Error message with guidance if cross-project move is detected, None otherwise
|
||||
"""
|
||||
try:
|
||||
# Get list of all available projects to check against
|
||||
response = await call_get(client, "/projects/projects")
|
||||
project_list = ProjectList.model_validate(response.json())
|
||||
project_names = [p.name.lower() for p in project_list.projects]
|
||||
|
||||
# Check if destination path contains any project names
|
||||
dest_lower = destination_path.lower()
|
||||
path_parts = dest_lower.split("/")
|
||||
|
||||
# Look for project names in the destination path
|
||||
for part in path_parts:
|
||||
if part in project_names and part != current_project.lower():
|
||||
# Found a different project name in the path
|
||||
matching_project = next(
|
||||
p.name for p in project_list.projects if p.name.lower() == part
|
||||
)
|
||||
return _format_cross_project_error_response(
|
||||
identifier, destination_path, current_project, matching_project
|
||||
)
|
||||
|
||||
# Check if the destination path looks like it might be trying to reference another project
|
||||
# (e.g., contains common project-like patterns)
|
||||
if any(keyword in dest_lower for keyword in ["project", "workspace", "repo"]):
|
||||
# This might be a cross-project attempt, but we can't be sure
|
||||
# Return a general guidance message
|
||||
available_projects = [
|
||||
p.name for p in project_list.projects if p.name != current_project
|
||||
]
|
||||
if available_projects:
|
||||
return _format_potential_cross_project_guidance(
|
||||
identifier, destination_path, current_project, available_projects
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
# If we can't detect, don't interfere with normal error handling
|
||||
logger.debug(f"Could not check for cross-project move: {e}")
|
||||
return None
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _format_cross_project_error_response(
|
||||
identifier: str, destination_path: str, current_project: str, target_project: str
|
||||
) -> str:
|
||||
"""Format error response for detected cross-project move attempts."""
|
||||
return dedent(f"""
|
||||
# Move Failed - Cross-Project Move Not Supported
|
||||
|
||||
Cannot move '{identifier}' to '{destination_path}' because it appears to reference a different project ('{target_project}').
|
||||
|
||||
**Current project:** {current_project}
|
||||
**Target project:** {target_project}
|
||||
|
||||
## Cross-project moves are not supported directly
|
||||
|
||||
Notes can only be moved within the same project. To move content between projects, use this workflow:
|
||||
|
||||
### Recommended approach:
|
||||
```
|
||||
# 1. Read the note content from current project
|
||||
read_note("{identifier}")
|
||||
|
||||
# 2. Switch to the target project
|
||||
switch_project("{target_project}")
|
||||
|
||||
# 3. Create the note in the target project
|
||||
write_note("Note Title", "content from step 1", "target-folder")
|
||||
|
||||
# 4. Switch back to original project (optional)
|
||||
switch_project("{current_project}")
|
||||
|
||||
# 5. Delete the original note if desired
|
||||
delete_note("{identifier}")
|
||||
```
|
||||
|
||||
### Alternative: Stay in current project
|
||||
If you want to move the note within the **{current_project}** project only:
|
||||
```
|
||||
move_note("{identifier}", "new-folder/new-name.md")
|
||||
```
|
||||
|
||||
## Available projects:
|
||||
Use `list_projects()` to see all available projects and `switch_project("project-name")` to change projects.
|
||||
""").strip()
|
||||
|
||||
|
||||
def _format_potential_cross_project_guidance(
|
||||
identifier: str, destination_path: str, current_project: str, available_projects: list[str]
|
||||
) -> str:
|
||||
"""Format guidance for potentially cross-project moves."""
|
||||
other_projects = ", ".join(available_projects[:3]) # Show first 3 projects
|
||||
if len(available_projects) > 3:
|
||||
other_projects += f" (and {len(available_projects) - 3} others)"
|
||||
|
||||
return dedent(f"""
|
||||
# Move Failed - Check Project Context
|
||||
|
||||
Cannot move '{identifier}' to '{destination_path}' within the current project '{current_project}'.
|
||||
|
||||
## If you intended to move within the current project:
|
||||
The destination path should be relative to the project root:
|
||||
```
|
||||
move_note("{identifier}", "folder/filename.md")
|
||||
```
|
||||
|
||||
## If you intended to move to a different project:
|
||||
Cross-project moves require switching projects first. Available projects: {other_projects}
|
||||
|
||||
### To move to another project:
|
||||
```
|
||||
# 1. Read the content
|
||||
read_note("{identifier}")
|
||||
|
||||
# 2. Switch to target project
|
||||
switch_project("target-project-name")
|
||||
|
||||
# 3. Create note in target project
|
||||
write_note("Title", "content", "folder")
|
||||
|
||||
# 4. Switch back and delete original if desired
|
||||
switch_project("{current_project}")
|
||||
delete_note("{identifier}")
|
||||
```
|
||||
|
||||
### To see all projects:
|
||||
```
|
||||
list_projects()
|
||||
```
|
||||
""").strip()
|
||||
|
||||
|
||||
def _format_move_error_response(error_message: str, identifier: str, destination_path: str) -> str:
|
||||
@@ -258,6 +404,14 @@ async def move_note(
|
||||
active_project = get_active_project(project)
|
||||
project_url = active_project.project_url
|
||||
|
||||
# Check for potential cross-project move attempts
|
||||
cross_project_error = await _detect_cross_project_move_attempt(
|
||||
identifier, destination_path, active_project.name
|
||||
)
|
||||
if cross_project_error:
|
||||
logger.info(f"Detected cross-project move attempt: {identifier} -> {destination_path}")
|
||||
return cross_project_error
|
||||
|
||||
try:
|
||||
# Prepare move request
|
||||
move_data = {
|
||||
|
||||
@@ -5,6 +5,7 @@ and manage project context during conversations.
|
||||
"""
|
||||
|
||||
from textwrap import dedent
|
||||
from typing import Optional
|
||||
|
||||
from fastmcp import Context
|
||||
from loguru import logger
|
||||
@@ -19,7 +20,9 @@ from basic_memory.utils import generate_permalink
|
||||
|
||||
|
||||
@mcp.tool("list_memory_projects")
|
||||
async def list_projects(ctx: Context | None = None) -> str:
|
||||
async def list_memory_projects(
|
||||
ctx: Context | None = None, _compatibility: Optional[str] = None
|
||||
) -> str:
|
||||
"""List all available projects with their status.
|
||||
|
||||
Shows all Basic Memory projects that are available, indicating which one
|
||||
@@ -29,7 +32,7 @@ async def list_projects(ctx: Context | None = None) -> str:
|
||||
Formatted list of projects with status indicators
|
||||
|
||||
Example:
|
||||
list_projects()
|
||||
list_memory_projects()
|
||||
"""
|
||||
if ctx: # pragma: no cover
|
||||
await ctx.info("Listing all available projects")
|
||||
@@ -144,13 +147,13 @@ async def switch_project(project_name: str, ctx: Context | None = None) -> str:
|
||||
Your session remains on the previous project.
|
||||
|
||||
## Troubleshooting:
|
||||
1. **Check available projects**: Use `list_projects()` to see valid project names
|
||||
1. **Check available projects**: Use `list_memory_projects()` to see valid project names
|
||||
2. **Verify spelling**: Ensure the project name is spelled correctly
|
||||
3. **Check permissions**: Verify you have access to the requested project
|
||||
4. **Try again**: The error might be temporary
|
||||
|
||||
## Available options:
|
||||
- See all projects: `list_projects()`
|
||||
- See all projects: `list_memory_projects()`
|
||||
- Stay on current project: `get_current_project()`
|
||||
- Try different project: `switch_project("correct-project-name")`
|
||||
|
||||
@@ -159,7 +162,9 @@ async def switch_project(project_name: str, ctx: Context | None = None) -> str:
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
async def get_current_project(ctx: Context | None = None) -> str:
|
||||
async def get_current_project(
|
||||
ctx: Context | None = None, _compatibility: Optional[str] = None
|
||||
) -> str:
|
||||
"""Show the currently active project and basic stats.
|
||||
|
||||
Displays which project is currently active and provides basic information
|
||||
@@ -231,7 +236,7 @@ async def set_default_project(project_name: str, ctx: Context | None = None) ->
|
||||
|
||||
|
||||
@mcp.tool("create_memory_project")
|
||||
async def create_project(
|
||||
async def create_memory_project(
|
||||
project_name: str, project_path: str, set_default: bool = False, ctx: Context | None = None
|
||||
) -> str:
|
||||
"""Create a new Basic Memory project.
|
||||
@@ -248,8 +253,8 @@ async def create_project(
|
||||
Confirmation message with project details
|
||||
|
||||
Example:
|
||||
create_project("my-research", "~/Documents/research")
|
||||
create_project("work-notes", "/home/user/work", set_default=True)
|
||||
create_memory_project("my-research", "~/Documents/research")
|
||||
create_memory_project("work-notes", "/home/user/work", set_default=True)
|
||||
"""
|
||||
if ctx: # pragma: no cover
|
||||
await ctx.info(f"Creating project: {project_name} at {project_path}")
|
||||
|
||||
@@ -52,14 +52,17 @@ async def read_note(
|
||||
read_note("Meeting Notes", project="work-project")
|
||||
"""
|
||||
|
||||
# Get the active project first to check project-specific sync status
|
||||
active_project = get_active_project(project)
|
||||
|
||||
# Check migration status and wait briefly if needed
|
||||
from basic_memory.mcp.tools.utils import wait_for_migration_or_return_status
|
||||
|
||||
migration_status = await wait_for_migration_or_return_status(timeout=5.0)
|
||||
migration_status = await wait_for_migration_or_return_status(
|
||||
timeout=5.0, project_name=active_project.name
|
||||
)
|
||||
if migration_status: # pragma: no cover
|
||||
return f"# System Status\n\n{migration_status}\n\nPlease wait for migration to complete before reading notes."
|
||||
|
||||
active_project = get_active_project(project)
|
||||
project_url = active_project.project_url
|
||||
|
||||
# Get the file via REST API - first try direct permalink lookup
|
||||
|
||||
@@ -45,13 +45,18 @@ def _format_search_error_response(error_message: str, query: str, search_type: s
|
||||
- Boolean OR: `meeting OR discussion`
|
||||
- Boolean NOT: `project NOT archived`
|
||||
- Grouped: `(project OR planning) AND notes`
|
||||
- Exact phrases: `"weekly standup meeting"`
|
||||
- Content-specific: `tag:example` or `category:observation`
|
||||
|
||||
## Try again with:
|
||||
```
|
||||
search_notes("INSERT_CLEAN_QUERY_HERE")
|
||||
search_notes("{clean_query}")
|
||||
```
|
||||
|
||||
Replace INSERT_CLEAN_QUERY_HERE with your simplified search terms.
|
||||
## Alternative search strategies:
|
||||
- Break into simpler terms: `search_notes("{" ".join(clean_query.split()[:2])}")`
|
||||
- Try different search types: `search_notes("{clean_query}", search_type="title")`
|
||||
- Use filtering: `search_notes("{clean_query}", types=["entity"])`
|
||||
""").strip()
|
||||
|
||||
# Project not found errors (check before general "not found")
|
||||
@@ -85,24 +90,39 @@ def _format_search_error_response(error_message: str, query: str, search_type: s
|
||||
|
||||
No content found matching '{query}' in the current project.
|
||||
|
||||
## Suggestions to try:
|
||||
## Search strategy suggestions:
|
||||
1. **Broaden your search**: Try fewer or more general terms
|
||||
- Instead of: `{query}`
|
||||
- Try: `{simplified_query}`
|
||||
|
||||
2. **Check spelling**: Verify terms are spelled correctly
|
||||
3. **Try different search types**:
|
||||
- Text search: `search_notes("{query}", search_type="text")`
|
||||
- Title search: `search_notes("{query}", search_type="title")`
|
||||
- Permalink search: `search_notes("{query}", search_type="permalink")`
|
||||
2. **Check spelling and try variations**:
|
||||
- Verify terms are spelled correctly
|
||||
- Try synonyms or related terms
|
||||
|
||||
4. **Use boolean operators**:
|
||||
- Try OR search for broader results
|
||||
3. **Use different search approaches**:
|
||||
- **Text search**: `search_notes("{query}", search_type="text")` (searches full content)
|
||||
- **Title search**: `search_notes("{query}", search_type="title")` (searches only titles)
|
||||
- **Permalink search**: `search_notes("{query}", search_type="permalink")` (searches file paths)
|
||||
|
||||
## Check what content exists:
|
||||
- Recent activity: `recent_activity(timeframe="7d")`
|
||||
- List files: `list_directory("/")`
|
||||
- Browse by folder: `list_directory("/notes")` or `list_directory("/docs")`
|
||||
4. **Try boolean operators for broader results**:
|
||||
- OR search: `search_notes("{" OR ".join(query.split()[:3])}")`
|
||||
- Remove restrictive terms: Focus on the most important keywords
|
||||
|
||||
5. **Use filtering to narrow scope**:
|
||||
- By content type: `search_notes("{query}", types=["entity"])`
|
||||
- By recent content: `search_notes("{query}", after_date="1 week")`
|
||||
- By entity type: `search_notes("{query}", entity_types=["observation"])`
|
||||
|
||||
6. **Try advanced search patterns**:
|
||||
- Tag search: `search_notes("tag:your-tag")`
|
||||
- Category search: `search_notes("category:observation")`
|
||||
- Pattern matching: `search_notes("*{query}*", search_type="permalink")`
|
||||
|
||||
## Explore what content exists:
|
||||
- **Recent activity**: `recent_activity(timeframe="7d")` - See what's been updated recently
|
||||
- **List directories**: `list_directory("/")` - Browse all content
|
||||
- **Browse by folder**: `list_directory("/notes")` or `list_directory("/docs")`
|
||||
- **Check project**: `get_current_project()` - Verify you're in the right project
|
||||
""").strip()
|
||||
|
||||
# Server/API errors
|
||||
@@ -151,25 +171,36 @@ You don't have permission to search in the current project: {error_message}
|
||||
|
||||
Error searching for '{query}': {error_message}
|
||||
|
||||
## General troubleshooting:
|
||||
1. **Check your query**: Ensure it uses valid search syntax
|
||||
2. **Try simpler terms**: Use basic words without special characters
|
||||
## Troubleshooting steps:
|
||||
1. **Simplify your query**: Try basic words without special characters
|
||||
2. **Check search syntax**: Ensure boolean operators are correctly formatted
|
||||
3. **Verify project access**: Make sure you can access the current project
|
||||
4. **Check recent activity**: `recent_activity(timeframe="7d")` to see if content exists
|
||||
4. **Test with simple search**: Try `search_notes("test")` to verify search is working
|
||||
|
||||
## Alternative approaches:
|
||||
- Browse files: `list_directory("/")`
|
||||
- Try different search type: `search_notes("{query}", search_type="title")`
|
||||
- Search with filters: `search_notes("{query}", types=["entity"])`
|
||||
## Alternative search approaches:
|
||||
- **Different search types**:
|
||||
- Title only: `search_notes("{query}", search_type="title")`
|
||||
- Permalink patterns: `search_notes("{query}*", search_type="permalink")`
|
||||
- **With filters**: `search_notes("{query}", types=["entity"])`
|
||||
- **Recent content**: `search_notes("{query}", after_date="1 week")`
|
||||
- **Boolean variations**: `search_notes("{" OR ".join(query.split()[:2])}")`
|
||||
|
||||
## Need help?
|
||||
- View recent changes: `recent_activity()`
|
||||
- List projects: `list_projects()`
|
||||
- Check current project: `get_current_project()`"""
|
||||
## Explore your content:
|
||||
- **Browse files**: `list_directory("/")` - See all available content
|
||||
- **Recent activity**: `recent_activity(timeframe="7d")` - Check what's been updated
|
||||
- **Project info**: `get_current_project()` - Verify current project
|
||||
- **All projects**: `list_projects()` - Switch to different project if needed
|
||||
|
||||
## Search syntax reference:
|
||||
- **Basic**: `keyword` or `multiple words`
|
||||
- **Boolean**: `term1 AND term2`, `term1 OR term2`, `term1 NOT term2`
|
||||
- **Phrases**: `"exact phrase"`
|
||||
- **Grouping**: `(term1 OR term2) AND term3`
|
||||
- **Patterns**: `tag:example`, `category:observation`"""
|
||||
|
||||
|
||||
@mcp.tool(
|
||||
description="Search across all content in the knowledge base.",
|
||||
description="Search across all content in the knowledge base with advanced syntax support.",
|
||||
)
|
||||
async def search_notes(
|
||||
query: str,
|
||||
@@ -181,24 +212,60 @@ async def search_notes(
|
||||
after_date: Optional[str] = None,
|
||||
project: Optional[str] = None,
|
||||
) -> SearchResponse | str:
|
||||
"""Search across all content in the knowledge base.
|
||||
"""Search across all content in the knowledge base with comprehensive syntax support.
|
||||
|
||||
This tool searches the knowledge base using full-text search, pattern matching,
|
||||
or exact permalink lookup. It supports filtering by content type, entity type,
|
||||
and date.
|
||||
and date, with advanced boolean and phrase search capabilities.
|
||||
|
||||
## Search Syntax Examples
|
||||
|
||||
### Basic Searches
|
||||
- `search_notes("keyword")` - Find any content containing "keyword"
|
||||
- `search_notes("exact phrase")` - Search for exact phrase match
|
||||
|
||||
### Advanced Boolean Searches
|
||||
- `search_notes("term1 term2")` - Find content with both terms (implicit AND)
|
||||
- `search_notes("term1 AND term2")` - Explicit AND search (both terms required)
|
||||
- `search_notes("term1 OR term2")` - Either term can be present
|
||||
- `search_notes("term1 NOT term2")` - Include term1 but exclude term2
|
||||
- `search_notes("(project OR planning) AND notes")` - Grouped boolean logic
|
||||
|
||||
### Content-Specific Searches
|
||||
- `search_notes("tag:example")` - Search within specific tags (if supported by content)
|
||||
- `search_notes("category:observation")` - Filter by observation categories
|
||||
- `search_notes("author:username")` - Find content by author (if metadata available)
|
||||
|
||||
### Search Type Examples
|
||||
- `search_notes("Meeting", search_type="title")` - Search only in titles
|
||||
- `search_notes("docs/meeting-*", search_type="permalink")` - Pattern match permalinks
|
||||
- `search_notes("keyword", search_type="text")` - Full-text search (default)
|
||||
|
||||
### Filtering Options
|
||||
- `search_notes("query", types=["entity"])` - Search only entities
|
||||
- `search_notes("query", types=["note", "person"])` - Multiple content types
|
||||
- `search_notes("query", entity_types=["observation"])` - Filter by entity type
|
||||
- `search_notes("query", after_date="2024-01-01")` - Recent content only
|
||||
- `search_notes("query", after_date="1 week")` - Relative date filtering
|
||||
|
||||
### Advanced Pattern Examples
|
||||
- `search_notes("project AND (meeting OR discussion)")` - Complex boolean logic
|
||||
- `search_notes("\"exact phrase\" AND keyword")` - Combine phrase and keyword search
|
||||
- `search_notes("bug NOT fixed")` - Exclude resolved issues
|
||||
- `search_notes("docs/2024-*", search_type="permalink")` - Year-based permalink search
|
||||
|
||||
Args:
|
||||
query: The search query string
|
||||
query: The search query string (supports boolean operators, phrases, patterns)
|
||||
page: The page number of results to return (default 1)
|
||||
page_size: The number of results to return per page (default 10)
|
||||
search_type: Type of search to perform, one of: "text", "title", "permalink" (default: "text")
|
||||
types: Optional list of note types to search (e.g., ["note", "person"])
|
||||
entity_types: Optional list of entity types to filter by (e.g., ["entity", "observation"])
|
||||
after_date: Optional date filter for recent content (e.g., "1 week", "2d")
|
||||
after_date: Optional date filter for recent content (e.g., "1 week", "2d", "2024-01-01")
|
||||
project: Optional project name to search in. If not provided, uses current active project.
|
||||
|
||||
Returns:
|
||||
SearchResponse with results and pagination info
|
||||
SearchResponse with results and pagination info, or helpful error guidance if search fails
|
||||
|
||||
Examples:
|
||||
# Basic text search
|
||||
@@ -216,16 +283,19 @@ async def search_notes(
|
||||
# Boolean search with grouping
|
||||
results = await search_notes("(project OR planning) AND notes")
|
||||
|
||||
# Exact phrase search
|
||||
results = await search_notes("\"weekly standup meeting\"")
|
||||
|
||||
# Search with type filter
|
||||
results = await search_notes(
|
||||
query="meeting notes",
|
||||
types=["entity"],
|
||||
)
|
||||
|
||||
# Search with entity type filter, e.g., note vs
|
||||
# Search with entity type filter
|
||||
results = await search_notes(
|
||||
query="meeting notes",
|
||||
types=["entity"],
|
||||
entity_types=["observation"],
|
||||
)
|
||||
|
||||
# Search for recent content
|
||||
@@ -242,6 +312,13 @@ async def search_notes(
|
||||
|
||||
# Search in specific project
|
||||
results = await search_notes("meeting notes", project="work-project")
|
||||
|
||||
# Complex search with multiple filters
|
||||
results = await search_notes(
|
||||
query="(bug OR issue) AND NOT resolved",
|
||||
types=["entity"],
|
||||
after_date="2024-01-01"
|
||||
)
|
||||
"""
|
||||
# Create a SearchQuery object based on the parameters
|
||||
search_query = SearchQuery()
|
||||
|
||||
@@ -525,11 +525,16 @@ def check_migration_status() -> Optional[str]:
|
||||
return None
|
||||
|
||||
|
||||
async def wait_for_migration_or_return_status(timeout: float = 5.0) -> Optional[str]:
|
||||
async def wait_for_migration_or_return_status(
|
||||
timeout: float = 5.0, project_name: Optional[str] = None
|
||||
) -> Optional[str]:
|
||||
"""Wait briefly for sync/migration to complete, or return status message.
|
||||
|
||||
Args:
|
||||
timeout: Maximum time to wait for sync completion
|
||||
project_name: Optional project name to check specific project status.
|
||||
If provided, only checks that project's readiness.
|
||||
If None, uses global status check (legacy behavior).
|
||||
|
||||
Returns:
|
||||
Status message if sync is still in progress, None if ready
|
||||
@@ -538,18 +543,36 @@ async def wait_for_migration_or_return_status(timeout: float = 5.0) -> Optional[
|
||||
from basic_memory.services.sync_status_service import sync_status_tracker
|
||||
import asyncio
|
||||
|
||||
if sync_status_tracker.is_ready:
|
||||
# Check if we should use project-specific or global status
|
||||
def is_ready() -> bool:
|
||||
if project_name:
|
||||
return sync_status_tracker.is_project_ready(project_name)
|
||||
return sync_status_tracker.is_ready
|
||||
|
||||
if is_ready():
|
||||
return None
|
||||
|
||||
# Wait briefly for sync to complete
|
||||
start_time = asyncio.get_event_loop().time()
|
||||
while (asyncio.get_event_loop().time() - start_time) < timeout:
|
||||
if sync_status_tracker.is_ready:
|
||||
if is_ready():
|
||||
return None
|
||||
await asyncio.sleep(0.1) # Check every 100ms
|
||||
|
||||
# Still not ready after timeout
|
||||
return sync_status_tracker.get_summary()
|
||||
if project_name:
|
||||
# For project-specific checks, get project status details
|
||||
project_status = sync_status_tracker.get_project_status(project_name)
|
||||
if project_status and project_status.status.value == "failed":
|
||||
error_msg = project_status.error or "Unknown sync error"
|
||||
return f"❌ Sync failed for project '{project_name}': {error_msg}"
|
||||
elif project_status:
|
||||
return f"🔄 Project '{project_name}' is still syncing: {project_status.message}"
|
||||
else:
|
||||
return f"⚠️ Project '{project_name}' status unknown"
|
||||
else:
|
||||
# Fall back to global summary for legacy calls
|
||||
return sync_status_tracker.get_summary()
|
||||
except Exception: # pragma: no cover
|
||||
# If there's any error, assume ready
|
||||
return None
|
||||
|
||||
@@ -72,10 +72,15 @@ async def write_note(
|
||||
"""
|
||||
logger.info(f"MCP tool call tool=write_note folder={folder}, title={title}, tags={tags}")
|
||||
|
||||
# Get the active project first to check project-specific sync status
|
||||
active_project = get_active_project(project)
|
||||
|
||||
# Check migration status and wait briefly if needed
|
||||
from basic_memory.mcp.tools.utils import wait_for_migration_or_return_status
|
||||
|
||||
migration_status = await wait_for_migration_or_return_status(timeout=5.0)
|
||||
migration_status = await wait_for_migration_or_return_status(
|
||||
timeout=5.0, project_name=active_project.name
|
||||
)
|
||||
if migration_status: # pragma: no cover
|
||||
return f"# System Status\n\n{migration_status}\n\nPlease wait for migration to complete before creating notes."
|
||||
|
||||
@@ -91,7 +96,6 @@ async def write_note(
|
||||
content=content,
|
||||
entity_metadata=metadata,
|
||||
)
|
||||
active_project = get_active_project(project)
|
||||
project_url = active_project.project_url
|
||||
|
||||
# Create or update via knowledge API
|
||||
|
||||
@@ -142,7 +142,7 @@ class EntityRepository(Repository[Entity]):
|
||||
await session.flush()
|
||||
# Return with relationships loaded
|
||||
query = (
|
||||
select(Entity)
|
||||
self.select()
|
||||
.where(Entity.file_path == entity.file_path)
|
||||
.options(*self.get_load_options())
|
||||
)
|
||||
@@ -162,7 +162,7 @@ class EntityRepository(Repository[Entity]):
|
||||
|
||||
# Return with relationships loaded
|
||||
query = (
|
||||
select(Entity)
|
||||
self.select()
|
||||
.where(Entity.file_path == entity.file_path)
|
||||
.options(*self.get_load_options())
|
||||
)
|
||||
@@ -203,7 +203,7 @@ class EntityRepository(Repository[Entity]):
|
||||
await session.flush()
|
||||
# Return the updated entity with relationships loaded
|
||||
query = (
|
||||
select(Entity)
|
||||
self.select()
|
||||
.where(Entity.file_path == entity.file_path)
|
||||
.options(*self.get_load_options())
|
||||
)
|
||||
@@ -243,7 +243,7 @@ class EntityRepository(Repository[Entity]):
|
||||
|
||||
# Return the inserted entity with relationships loaded
|
||||
query = (
|
||||
select(Entity)
|
||||
self.select()
|
||||
.where(Entity.file_path == entity.file_path)
|
||||
.options(*self.get_load_options())
|
||||
)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Repository for search operations."""
|
||||
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
@@ -120,23 +121,141 @@ class SearchRepository:
|
||||
logger.error(f"Error initializing search index: {e}")
|
||||
raise e
|
||||
|
||||
def _prepare_search_term(self, term: str, is_prefix: bool = True) -> str:
|
||||
"""Prepare a search term for FTS5 query.
|
||||
def _prepare_boolean_query(self, query: str) -> str:
|
||||
"""Prepare a Boolean query by quoting individual terms while preserving operators.
|
||||
|
||||
Args:
|
||||
term: The search term to prepare
|
||||
query: A Boolean query like "tier1-test AND unicode" or "(hello OR world) NOT test"
|
||||
|
||||
Returns:
|
||||
A properly formatted Boolean query with quoted terms that need quoting
|
||||
"""
|
||||
# Define Boolean operators and their boundaries
|
||||
boolean_pattern = r"(\bAND\b|\bOR\b|\bNOT\b)"
|
||||
|
||||
# Split the query by Boolean operators, keeping the operators
|
||||
parts = re.split(boolean_pattern, query)
|
||||
|
||||
processed_parts = []
|
||||
for part in parts:
|
||||
part = part.strip()
|
||||
if not part:
|
||||
continue
|
||||
|
||||
# If it's a Boolean operator, keep it as is
|
||||
if part in ["AND", "OR", "NOT"]:
|
||||
processed_parts.append(part)
|
||||
else:
|
||||
# Handle parentheses specially - they should be preserved for grouping
|
||||
if "(" in part or ")" in part:
|
||||
# Parse parenthetical expressions carefully
|
||||
processed_part = self._prepare_parenthetical_term(part)
|
||||
processed_parts.append(processed_part)
|
||||
else:
|
||||
# This is a search term - for Boolean queries, don't add prefix wildcards
|
||||
prepared_term = self._prepare_single_term(part, is_prefix=False)
|
||||
processed_parts.append(prepared_term)
|
||||
|
||||
return " ".join(processed_parts)
|
||||
|
||||
def _prepare_parenthetical_term(self, term: str) -> str:
|
||||
"""Prepare a term that contains parentheses, preserving the parentheses for grouping.
|
||||
|
||||
Args:
|
||||
term: A term that may contain parentheses like "(hello" or "world)" or "(hello OR world)"
|
||||
|
||||
Returns:
|
||||
A properly formatted term with parentheses preserved
|
||||
"""
|
||||
# Handle terms that start/end with parentheses but may contain quotable content
|
||||
result = ""
|
||||
i = 0
|
||||
while i < len(term):
|
||||
if term[i] in "()":
|
||||
# Preserve parentheses as-is
|
||||
result += term[i]
|
||||
i += 1
|
||||
else:
|
||||
# Find the next parenthesis or end of string
|
||||
start = i
|
||||
while i < len(term) and term[i] not in "()":
|
||||
i += 1
|
||||
|
||||
# Extract the content between parentheses
|
||||
content = term[start:i].strip()
|
||||
if content:
|
||||
# Only quote if it actually needs quoting (has hyphens, special chars, etc)
|
||||
# but don't quote if it's just simple words
|
||||
if self._needs_quoting(content):
|
||||
escaped_content = content.replace('"', '""')
|
||||
result += f'"{escaped_content}"'
|
||||
else:
|
||||
result += content
|
||||
|
||||
return result
|
||||
|
||||
def _needs_quoting(self, term: str) -> bool:
|
||||
"""Check if a term needs to be quoted for FTS5 safety.
|
||||
|
||||
Args:
|
||||
term: The term to check
|
||||
|
||||
Returns:
|
||||
True if the term should be quoted
|
||||
"""
|
||||
if not term or not term.strip():
|
||||
return False
|
||||
|
||||
# Characters that indicate we should quote (excluding parentheses which are valid syntax)
|
||||
needs_quoting_chars = [
|
||||
" ",
|
||||
".",
|
||||
":",
|
||||
";",
|
||||
",",
|
||||
"<",
|
||||
">",
|
||||
"?",
|
||||
"/",
|
||||
"-",
|
||||
"'",
|
||||
'"',
|
||||
"[",
|
||||
"]",
|
||||
"{",
|
||||
"}",
|
||||
"+",
|
||||
"!",
|
||||
"@",
|
||||
"#",
|
||||
"$",
|
||||
"%",
|
||||
"^",
|
||||
"&",
|
||||
"=",
|
||||
"|",
|
||||
"\\",
|
||||
"~",
|
||||
"`",
|
||||
]
|
||||
|
||||
return any(c in term for c in needs_quoting_chars)
|
||||
|
||||
def _prepare_single_term(self, term: str, is_prefix: bool = True) -> str:
|
||||
"""Prepare a single search term (no Boolean operators).
|
||||
|
||||
Args:
|
||||
term: A single search term
|
||||
is_prefix: Whether to add prefix search capability (* suffix)
|
||||
|
||||
For FTS5:
|
||||
- Boolean operators (AND, OR, NOT) are preserved for complex queries
|
||||
- Terms with FTS5 special characters are quoted to prevent syntax errors
|
||||
- Simple terms get prefix wildcards for better matching
|
||||
Returns:
|
||||
A properly formatted single term
|
||||
"""
|
||||
# Check for explicit boolean operators - if present, return the term as is
|
||||
boolean_operators = [" AND ", " OR ", " NOT "]
|
||||
if any(op in f" {term} " for op in boolean_operators):
|
||||
if not term or not term.strip():
|
||||
return term
|
||||
|
||||
term = term.strip()
|
||||
|
||||
# Check if term is already a proper wildcard pattern (alphanumeric + *)
|
||||
# e.g., "hello*", "test*world" - these should be left alone
|
||||
if "*" in term and all(c.isalnum() or c in "*_-" for c in term):
|
||||
@@ -218,6 +337,26 @@ class SearchRepository:
|
||||
|
||||
return term
|
||||
|
||||
def _prepare_search_term(self, term: str, is_prefix: bool = True) -> str:
|
||||
"""Prepare a search term for FTS5 query.
|
||||
|
||||
Args:
|
||||
term: The search term to prepare
|
||||
is_prefix: Whether to add prefix search capability (* suffix)
|
||||
|
||||
For FTS5:
|
||||
- Boolean operators (AND, OR, NOT) are preserved for complex queries
|
||||
- Terms with FTS5 special characters are quoted to prevent syntax errors
|
||||
- Simple terms get prefix wildcards for better matching
|
||||
"""
|
||||
# Check for explicit boolean operators - if present, process as Boolean query
|
||||
boolean_operators = [" AND ", " OR ", " NOT "]
|
||||
if any(op in f" {term} " for op in boolean_operators):
|
||||
return self._prepare_boolean_query(term)
|
||||
|
||||
# For non-Boolean queries, use the single term preparation logic
|
||||
return self._prepare_single_term(term, is_prefix)
|
||||
|
||||
async def search(
|
||||
self,
|
||||
search_text: Optional[str] = None,
|
||||
@@ -242,19 +381,10 @@ class SearchRepository:
|
||||
# For wildcard searches, don't add any text conditions - return all results
|
||||
pass
|
||||
else:
|
||||
# Check for explicit boolean operators - only detect them in proper boolean contexts
|
||||
has_boolean = any(op in f" {search_text} " for op in [" AND ", " OR ", " NOT "])
|
||||
|
||||
if has_boolean:
|
||||
# If boolean operators are present, use the raw query
|
||||
# No need to prepare it, FTS5 will understand the operators
|
||||
params["text"] = search_text
|
||||
conditions.append("(title MATCH :text OR content_stems MATCH :text)")
|
||||
else:
|
||||
# Standard search with term preparation
|
||||
processed_text = self._prepare_search_term(search_text.strip())
|
||||
params["text"] = processed_text
|
||||
conditions.append("(title MATCH :text OR content_stems MATCH :text)")
|
||||
# Use _prepare_search_term to handle both Boolean and non-Boolean queries
|
||||
processed_text = self._prepare_search_term(search_text.strip())
|
||||
params["text"] = processed_text
|
||||
conditions.append("(title MATCH :text OR content_stems MATCH :text)")
|
||||
|
||||
# Handle title match search
|
||||
if title:
|
||||
|
||||
@@ -134,7 +134,7 @@ class RelationSummary(BaseModel):
|
||||
file_path: str
|
||||
permalink: str
|
||||
relation_type: str
|
||||
from_entity: str
|
||||
from_entity: Optional[str] = None
|
||||
to_entity: Optional[str] = None
|
||||
created_at: datetime
|
||||
|
||||
|
||||
@@ -131,7 +131,7 @@ class EntityResponse(SQLAlchemyModel):
|
||||
}
|
||||
"""
|
||||
|
||||
permalink: Permalink
|
||||
permalink: Optional[Permalink]
|
||||
title: str
|
||||
file_path: str
|
||||
entity_type: EntityType
|
||||
|
||||
@@ -682,8 +682,8 @@ class EntityService(BaseService[EntityModel]):
|
||||
# 6. Prepare database updates
|
||||
updates = {"file_path": destination_path}
|
||||
|
||||
# 7. Update permalink if configured
|
||||
if app_config.update_permalinks_on_move:
|
||||
# 7. Update permalink if configured or if entity has null permalink
|
||||
if app_config.update_permalinks_on_move or old_permalink is None:
|
||||
# Generate new permalink from destination path
|
||||
new_permalink = await self.resolve_permalink(destination_path)
|
||||
|
||||
@@ -693,7 +693,12 @@ class EntityService(BaseService[EntityModel]):
|
||||
)
|
||||
|
||||
updates["permalink"] = new_permalink
|
||||
logger.info(f"Updated permalink: {old_permalink} -> {new_permalink}")
|
||||
if old_permalink is None:
|
||||
logger.info(
|
||||
f"Generated permalink for entity with null permalink: {new_permalink}"
|
||||
)
|
||||
else:
|
||||
logger.info(f"Updated permalink: {old_permalink} -> {new_permalink}")
|
||||
|
||||
# 8. Recalculate checksum
|
||||
new_checksum = await self.file_service.compute_checksum(destination_path)
|
||||
|
||||
@@ -131,6 +131,23 @@ class SyncStatusTracker:
|
||||
"""Check if system is ready (no sync in progress)."""
|
||||
return self._global_status in (SyncStatus.IDLE, SyncStatus.COMPLETED)
|
||||
|
||||
def is_project_ready(self, project_name: str) -> bool:
|
||||
"""Check if a specific project is ready for operations.
|
||||
|
||||
Args:
|
||||
project_name: Name of the project to check
|
||||
|
||||
Returns:
|
||||
True if the project is ready (completed, watching, or not tracked),
|
||||
False if the project is syncing, scanning, or failed
|
||||
"""
|
||||
project_status = self._project_statuses.get(project_name)
|
||||
if not project_status:
|
||||
# Project not tracked = ready (likely hasn't been synced yet)
|
||||
return True
|
||||
|
||||
return project_status.status in (SyncStatus.COMPLETED, SyncStatus.WATCHING, SyncStatus.IDLE)
|
||||
|
||||
def get_project_status(self, project_name: str) -> Optional[ProjectSyncStatus]:
|
||||
"""Get status for a specific project."""
|
||||
return self._project_statuses.get(project_name)
|
||||
|
||||
@@ -173,6 +173,8 @@ def setup_logging(
|
||||
"httpx": logging.WARNING,
|
||||
# File watching logs
|
||||
"watchfiles.main": logging.WARNING,
|
||||
# SQLAlchemy deprecation warnings
|
||||
"sqlalchemy": logging.WARNING,
|
||||
}
|
||||
|
||||
# Set log levels for noisy loggers
|
||||
|
||||
@@ -507,3 +507,136 @@ async def test_move_note_using_different_identifier_formats(mcp_server, app):
|
||||
|
||||
read3 = await client.call_tool("read_note", {"identifier": "moved/folder-title-moved.md"})
|
||||
assert "Move by folder/title" in read3[0].text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_move_note_cross_project_detection(mcp_server, app):
|
||||
"""Test cross-project move detection and helpful error messages."""
|
||||
|
||||
async with Client(mcp_server) as client:
|
||||
# Create a test project to simulate cross-project scenario
|
||||
await client.call_tool(
|
||||
"create_memory_project",
|
||||
{
|
||||
"project_name": "test-project-b",
|
||||
"project_path": "/tmp/test-project-b",
|
||||
"set_default": False,
|
||||
},
|
||||
)
|
||||
|
||||
# Create a note in the default project
|
||||
await client.call_tool(
|
||||
"write_note",
|
||||
{
|
||||
"title": "Cross Project Test Note",
|
||||
"folder": "source",
|
||||
"content": "# Cross Project Test Note\n\nThis note is in the default project.",
|
||||
"tags": "test,cross-project",
|
||||
},
|
||||
)
|
||||
|
||||
# Try to move to a path that contains the other project name
|
||||
move_result = await client.call_tool(
|
||||
"move_note",
|
||||
{
|
||||
"identifier": "Cross Project Test Note",
|
||||
"destination_path": "test-project-b/moved-note.md",
|
||||
},
|
||||
)
|
||||
|
||||
# Should detect cross-project attempt and provide helpful guidance
|
||||
assert len(move_result) == 1
|
||||
error_message = move_result[0].text
|
||||
assert "Cross-Project Move Not Supported" in error_message
|
||||
assert "test-project-b" in error_message
|
||||
assert "switch_project" in error_message
|
||||
assert "read_note" in error_message
|
||||
assert "write_note" in error_message
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_move_note_potential_cross_project_guidance(mcp_server, app):
|
||||
"""Test guidance for potentially cross-project moves with project-like keywords."""
|
||||
|
||||
async with Client(mcp_server) as client:
|
||||
# Create another test project
|
||||
await client.call_tool(
|
||||
"create_memory_project",
|
||||
{
|
||||
"project_name": "workspace-docs",
|
||||
"project_path": "/tmp/workspace-docs",
|
||||
"set_default": False,
|
||||
},
|
||||
)
|
||||
|
||||
# Create a note in the default project
|
||||
await client.call_tool(
|
||||
"write_note",
|
||||
{
|
||||
"title": "Potential Cross Project Note",
|
||||
"folder": "source",
|
||||
"content": "# Potential Cross Project Note\n\nThis might be moved cross-project.",
|
||||
"tags": "test,potential-cross-project",
|
||||
},
|
||||
)
|
||||
|
||||
# Try to move to a path that contains project-like keywords but not exact project names
|
||||
move_result = await client.call_tool(
|
||||
"move_note",
|
||||
{
|
||||
"identifier": "Potential Cross Project Note",
|
||||
"destination_path": "project-archive/moved-note.md",
|
||||
},
|
||||
)
|
||||
|
||||
# Should provide guidance for potential cross-project moves
|
||||
assert len(move_result) == 1
|
||||
error_message = move_result[0].text
|
||||
assert "Check Project Context" in error_message
|
||||
assert "workspace-docs" in error_message # Should mention other available projects
|
||||
assert "list_projects" in error_message
|
||||
assert "switch_project" in error_message
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_move_note_normal_moves_still_work(mcp_server, app):
|
||||
"""Test that normal within-project moves still work after cross-project detection."""
|
||||
|
||||
async with Client(mcp_server) as client:
|
||||
# Create a note
|
||||
await client.call_tool(
|
||||
"write_note",
|
||||
{
|
||||
"title": "Normal Move Note",
|
||||
"folder": "source",
|
||||
"content": "# Normal Move Note\n\nThis should move normally.",
|
||||
"tags": "test,normal-move",
|
||||
},
|
||||
)
|
||||
|
||||
# Try a normal move that should work
|
||||
move_result = await client.call_tool(
|
||||
"move_note",
|
||||
{
|
||||
"identifier": "Normal Move Note",
|
||||
"destination_path": "destination/normal-moved.md",
|
||||
},
|
||||
)
|
||||
|
||||
# Should work normally
|
||||
assert len(move_result) == 1
|
||||
move_text = move_result[0].text
|
||||
assert "✅ Note moved successfully" in move_text
|
||||
assert "Normal Move Note" in move_text
|
||||
assert "destination/normal-moved.md" in move_text
|
||||
|
||||
# Verify the note can be read from its new location
|
||||
read_result = await client.call_tool(
|
||||
"read_note",
|
||||
{
|
||||
"identifier": "destination/normal-moved.md",
|
||||
},
|
||||
)
|
||||
|
||||
content = read_result[0].text
|
||||
assert "This should move normally" in content
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""Tests for OAuth authentication provider."""
|
||||
|
||||
import pytest
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from mcp.server.auth.provider import AuthorizationParams
|
||||
from mcp.shared.auth import OAuthClientInformationFull
|
||||
from pydantic import AnyHttpUrl
|
||||
@@ -185,7 +185,7 @@ class TestBasicMemoryOAuthProvider:
|
||||
token=token_str,
|
||||
client_id=client.client_id,
|
||||
scopes=["read", "write"],
|
||||
expires_at=int((datetime.utcnow() + timedelta(hours=1)).timestamp()),
|
||||
expires_at=int((datetime.now(timezone.utc) + timedelta(hours=1)).timestamp()),
|
||||
)
|
||||
provider.access_tokens[token_str] = access_token
|
||||
|
||||
@@ -226,7 +226,7 @@ class TestBasicMemoryOAuthProvider:
|
||||
provider.authorization_codes[auth_code] = BasicMemoryAuthorizationCode(
|
||||
code=auth_code,
|
||||
scopes=["read"],
|
||||
expires_at=(datetime.utcnow() - timedelta(minutes=1)).timestamp(),
|
||||
expires_at=(datetime.now(timezone.utc) - timedelta(minutes=1)).timestamp(),
|
||||
client_id=client.client_id,
|
||||
code_challenge="challenge",
|
||||
redirect_uri=AnyHttpUrl("http://localhost:3000/callback"),
|
||||
@@ -288,7 +288,7 @@ class TestBasicMemoryOAuthProvider:
|
||||
token=expired_token_str,
|
||||
client_id="test-client",
|
||||
scopes=["read"],
|
||||
expires_at=int((datetime.utcnow() - timedelta(minutes=1)).timestamp()), # Expired
|
||||
expires_at=int((datetime.now(timezone.utc) - timedelta(minutes=1)).timestamp()), # Expired
|
||||
)
|
||||
provider.access_tokens[expired_token_str] = expired_access_token
|
||||
|
||||
|
||||
@@ -93,7 +93,7 @@ class TestMCPServer:
|
||||
# Missing SUPABASE_ANON_KEY
|
||||
}
|
||||
|
||||
with patch.dict(os.environ, env_vars):
|
||||
with patch.dict(os.environ, env_vars, clear=True):
|
||||
with pytest.raises(ValueError, match="SUPABASE_URL and SUPABASE_ANON_KEY must be set"):
|
||||
create_auth_config()
|
||||
|
||||
|
||||
@@ -359,3 +359,42 @@ async def test_edit_note_find_replace_empty_find_text(client):
|
||||
assert isinstance(result, str)
|
||||
assert "# Edit Failed" in result
|
||||
# Should contain helpful guidance about the error
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_edit_note_preserves_permalink_when_frontmatter_missing(client):
|
||||
"""Test that editing a note preserves the permalink when frontmatter doesn't contain one.
|
||||
|
||||
This is a regression test for issue #170 where edit_note would fail with a validation error
|
||||
because the permalink was being set to None when the markdown file didn't have a permalink
|
||||
in its frontmatter.
|
||||
"""
|
||||
# Create initial note
|
||||
await write_note.fn(
|
||||
title="Test Note",
|
||||
folder="test",
|
||||
content="# Test Note\nOriginal content here.",
|
||||
)
|
||||
|
||||
# Verify the note was created with a permalink
|
||||
first_result = await edit_note.fn(
|
||||
identifier="test/test-note",
|
||||
operation="append",
|
||||
content="\nFirst edit.",
|
||||
)
|
||||
|
||||
assert isinstance(first_result, str)
|
||||
assert "permalink: test/test-note" in first_result
|
||||
|
||||
# Perform another edit - this should preserve the permalink even if the
|
||||
# file doesn't have a permalink in its frontmatter
|
||||
second_result = await edit_note.fn(
|
||||
identifier="test/test-note",
|
||||
operation="append",
|
||||
content="\nSecond edit.",
|
||||
)
|
||||
|
||||
assert isinstance(second_result, str)
|
||||
assert "Edited note (append)" in second_result
|
||||
assert "permalink: test/test-note" in second_result
|
||||
# The edit should succeed without validation errors
|
||||
|
||||
@@ -6,6 +6,7 @@ from unittest.mock import patch
|
||||
|
||||
from basic_memory.mcp.tools import write_note
|
||||
from basic_memory.mcp.tools.search import search_notes, _format_search_error_response
|
||||
from basic_memory.schemas.search import SearchResponse
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -23,9 +24,14 @@ async def test_search_text(client):
|
||||
# Search for it
|
||||
response = await search_notes.fn(query="searchable")
|
||||
|
||||
# Verify results
|
||||
assert len(response.results) > 0
|
||||
assert any(r.permalink == "test/test-search-note" for r in response.results)
|
||||
# Verify results - handle both success and error cases
|
||||
if isinstance(response, SearchResponse):
|
||||
# Success case - verify SearchResponse
|
||||
assert len(response.results) > 0
|
||||
assert any(r.permalink == "test/test-search-note" for r in response.results)
|
||||
else:
|
||||
# If search failed and returned error message, test should fail with informative message
|
||||
pytest.fail(f"Search failed with error: {response}")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -43,9 +49,14 @@ async def test_search_title(client):
|
||||
# Search for it
|
||||
response = await search_notes.fn(query="Search Note", search_type="title")
|
||||
|
||||
# Verify results
|
||||
assert len(response.results) > 0
|
||||
assert any(r.permalink == "test/test-search-note" for r in response.results)
|
||||
# Verify results - handle both success and error cases
|
||||
if isinstance(response, str):
|
||||
# If search failed and returned error message, test should fail with informative message
|
||||
pytest.fail(f"Search failed with error: {response}")
|
||||
else:
|
||||
# Success case - verify SearchResponse
|
||||
assert len(response.results) > 0
|
||||
assert any(r.permalink == "test/test-search-note" for r in response.results)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -63,9 +74,14 @@ async def test_search_permalink(client):
|
||||
# Search for it
|
||||
response = await search_notes.fn(query="test/test-search-note", search_type="permalink")
|
||||
|
||||
# Verify results
|
||||
assert len(response.results) > 0
|
||||
assert any(r.permalink == "test/test-search-note" for r in response.results)
|
||||
# Verify results - handle both success and error cases
|
||||
if isinstance(response, SearchResponse):
|
||||
# Success case - verify SearchResponse
|
||||
assert len(response.results) > 0
|
||||
assert any(r.permalink == "test/test-search-note" for r in response.results)
|
||||
else:
|
||||
# If search failed and returned error message, test should fail with informative message
|
||||
pytest.fail(f"Search failed with error: {response}")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -83,9 +99,14 @@ async def test_search_permalink_match(client):
|
||||
# Search for it
|
||||
response = await search_notes.fn(query="test/test-search-*", search_type="permalink")
|
||||
|
||||
# Verify results
|
||||
assert len(response.results) > 0
|
||||
assert any(r.permalink == "test/test-search-note" for r in response.results)
|
||||
# Verify results - handle both success and error cases
|
||||
if isinstance(response, SearchResponse):
|
||||
# Success case - verify SearchResponse
|
||||
assert len(response.results) > 0
|
||||
assert any(r.permalink == "test/test-search-note" for r in response.results)
|
||||
else:
|
||||
# If search failed and returned error message, test should fail with informative message
|
||||
pytest.fail(f"Search failed with error: {response}")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -103,9 +124,14 @@ async def test_search_pagination(client):
|
||||
# Search for it
|
||||
response = await search_notes.fn(query="searchable", page=1, page_size=1)
|
||||
|
||||
# Verify results
|
||||
assert len(response.results) == 1
|
||||
assert any(r.permalink == "test/test-search-note" for r in response.results)
|
||||
# Verify results - handle both success and error cases
|
||||
if isinstance(response, SearchResponse):
|
||||
# Success case - verify SearchResponse
|
||||
assert len(response.results) == 1
|
||||
assert any(r.permalink == "test/test-search-note" for r in response.results)
|
||||
else:
|
||||
# If search failed and returned error message, test should fail with informative message
|
||||
pytest.fail(f"Search failed with error: {response}")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -121,8 +147,13 @@ async def test_search_with_type_filter(client):
|
||||
# Search with type filter
|
||||
response = await search_notes.fn(query="type", types=["note"])
|
||||
|
||||
# Verify all results are entities
|
||||
assert all(r.type == "entity" for r in response.results)
|
||||
# Verify results - handle both success and error cases
|
||||
if isinstance(response, SearchResponse):
|
||||
# Success case - verify all results are entities
|
||||
assert all(r.type == "entity" for r in response.results)
|
||||
else:
|
||||
# If search failed and returned error message, test should fail with informative message
|
||||
pytest.fail(f"Search failed with error: {response}")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -138,8 +169,13 @@ async def test_search_with_entity_type_filter(client):
|
||||
# Search with entity type filter
|
||||
response = await search_notes.fn(query="type", entity_types=["entity"])
|
||||
|
||||
# Verify all results are entities
|
||||
assert all(r.type == "entity" for r in response.results)
|
||||
# Verify results - handle both success and error cases
|
||||
if isinstance(response, SearchResponse):
|
||||
# Success case - verify all results are entities
|
||||
assert all(r.type == "entity" for r in response.results)
|
||||
else:
|
||||
# If search failed and returned error message, test should fail with informative message
|
||||
pytest.fail(f"Search failed with error: {response}")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -156,8 +192,13 @@ async def test_search_with_date_filter(client):
|
||||
one_hour_ago = datetime.now() - timedelta(hours=1)
|
||||
response = await search_notes.fn(query="recent", after_date=one_hour_ago.isoformat())
|
||||
|
||||
# Verify we get results within timeframe
|
||||
assert len(response.results) > 0
|
||||
# Verify results - handle both success and error cases
|
||||
if isinstance(response, SearchResponse):
|
||||
# Success case - verify we get results within timeframe
|
||||
assert len(response.results) > 0
|
||||
else:
|
||||
# If search failed and returned error message, test should fail with informative message
|
||||
pytest.fail(f"Search failed with error: {response}")
|
||||
|
||||
|
||||
class TestSearchErrorFormatting:
|
||||
@@ -212,7 +253,7 @@ class TestSearchErrorFormatting:
|
||||
|
||||
assert "# Search Failed" in result
|
||||
assert "Error searching for 'test query': unknown error" in result
|
||||
assert "General troubleshooting" in result
|
||||
assert "## Troubleshooting steps:" in result
|
||||
|
||||
|
||||
class TestSearchToolErrorHandling:
|
||||
|
||||
@@ -5,6 +5,7 @@ from datetime import datetime, timezone
|
||||
|
||||
from basic_memory.models.knowledge import Entity
|
||||
from basic_memory.repository.entity_repository import EntityRepository
|
||||
from basic_memory.repository.project_repository import ProjectRepository
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -246,3 +247,205 @@ async def test_upsert_entity_gap_in_suffixes(entity_repository: EntityRepository
|
||||
# so it should be "test/gap-2" (filling the gap)
|
||||
assert result.permalink == "test/gap-2"
|
||||
assert result.title == "Gap Filler"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upsert_entity_project_scoping_isolation(session_maker):
|
||||
"""Test that upsert_entity properly scopes entities by project_id.
|
||||
|
||||
This test ensures that the fix for issue #167 works correctly by verifying:
|
||||
1. Entities with same permalinks/file_paths can exist in different projects
|
||||
2. Upsert operations properly scope queries by project_id
|
||||
3. No "multiple rows" errors occur when similar entities exist across projects
|
||||
"""
|
||||
# Create two separate projects
|
||||
project_repository = ProjectRepository(session_maker)
|
||||
|
||||
project1_data = {
|
||||
"name": "project-1",
|
||||
"description": "First test project",
|
||||
"path": "/tmp/project1",
|
||||
"is_active": True,
|
||||
"is_default": False,
|
||||
}
|
||||
project1 = await project_repository.create(project1_data)
|
||||
|
||||
project2_data = {
|
||||
"name": "project-2",
|
||||
"description": "Second test project",
|
||||
"path": "/tmp/project2",
|
||||
"is_active": True,
|
||||
"is_default": False,
|
||||
}
|
||||
project2 = await project_repository.create(project2_data)
|
||||
|
||||
# Create entity repositories for each project
|
||||
repo1 = EntityRepository(session_maker, project_id=project1.id)
|
||||
repo2 = EntityRepository(session_maker, project_id=project2.id)
|
||||
|
||||
# Create entities with identical permalinks and file_paths in different projects
|
||||
entity1 = Entity(
|
||||
project_id=project1.id,
|
||||
title="Shared Entity",
|
||||
entity_type="note",
|
||||
permalink="docs/shared-name",
|
||||
file_path="docs/shared-name.md",
|
||||
content_type="text/markdown",
|
||||
created_at=datetime.now(timezone.utc),
|
||||
updated_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
entity2 = Entity(
|
||||
project_id=project2.id,
|
||||
title="Shared Entity",
|
||||
entity_type="note",
|
||||
permalink="docs/shared-name", # Same permalink
|
||||
file_path="docs/shared-name.md", # Same file_path
|
||||
content_type="text/markdown",
|
||||
created_at=datetime.now(timezone.utc),
|
||||
updated_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
# These should succeed without "multiple rows" errors
|
||||
result1 = await repo1.upsert_entity(entity1)
|
||||
result2 = await repo2.upsert_entity(entity2)
|
||||
|
||||
# Verify both entities were created successfully
|
||||
assert result1.id is not None
|
||||
assert result2.id is not None
|
||||
assert result1.id != result2.id # Different entities
|
||||
assert result1.project_id == project1.id
|
||||
assert result2.project_id == project2.id
|
||||
assert result1.permalink == "docs/shared-name"
|
||||
assert result2.permalink == "docs/shared-name"
|
||||
|
||||
# Test updating entities in different projects (should also work without conflicts)
|
||||
entity1_update = Entity(
|
||||
project_id=project1.id,
|
||||
title="Updated Shared Entity",
|
||||
entity_type="note",
|
||||
permalink="docs/shared-name",
|
||||
file_path="docs/shared-name.md",
|
||||
content_type="text/markdown",
|
||||
created_at=datetime.now(timezone.utc),
|
||||
updated_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
entity2_update = Entity(
|
||||
project_id=project2.id,
|
||||
title="Also Updated Shared Entity",
|
||||
entity_type="note",
|
||||
permalink="docs/shared-name",
|
||||
file_path="docs/shared-name.md",
|
||||
content_type="text/markdown",
|
||||
created_at=datetime.now(timezone.utc),
|
||||
updated_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
# Updates should work without conflicts
|
||||
updated1 = await repo1.upsert_entity(entity1_update)
|
||||
updated2 = await repo2.upsert_entity(entity2_update)
|
||||
|
||||
# Should update existing entities (same IDs)
|
||||
assert updated1.id == result1.id
|
||||
assert updated2.id == result2.id
|
||||
assert updated1.title == "Updated Shared Entity"
|
||||
assert updated2.title == "Also Updated Shared Entity"
|
||||
|
||||
# Verify cross-project queries don't interfere
|
||||
found_in_project1 = await repo1.get_by_permalink("docs/shared-name")
|
||||
found_in_project2 = await repo2.get_by_permalink("docs/shared-name")
|
||||
|
||||
assert found_in_project1 is not None
|
||||
assert found_in_project2 is not None
|
||||
assert found_in_project1.id == updated1.id
|
||||
assert found_in_project2.id == updated2.id
|
||||
assert found_in_project1.title == "Updated Shared Entity"
|
||||
assert found_in_project2.title == "Also Updated Shared Entity"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upsert_entity_permalink_conflict_within_project_only(session_maker):
|
||||
"""Test that permalink conflicts only occur within the same project.
|
||||
|
||||
This ensures that the project scoping fix allows entities with identical
|
||||
permalinks to exist across different projects without triggering
|
||||
permalink conflict resolution.
|
||||
"""
|
||||
# Create two separate projects
|
||||
project_repository = ProjectRepository(session_maker)
|
||||
|
||||
project1_data = {
|
||||
"name": "conflict-project-1",
|
||||
"description": "First conflict test project",
|
||||
"path": "/tmp/conflict1",
|
||||
"is_active": True,
|
||||
"is_default": False,
|
||||
}
|
||||
project1 = await project_repository.create(project1_data)
|
||||
|
||||
project2_data = {
|
||||
"name": "conflict-project-2",
|
||||
"description": "Second conflict test project",
|
||||
"path": "/tmp/conflict2",
|
||||
"is_active": True,
|
||||
"is_default": False,
|
||||
}
|
||||
project2 = await project_repository.create(project2_data)
|
||||
|
||||
# Create entity repositories for each project
|
||||
repo1 = EntityRepository(session_maker, project_id=project1.id)
|
||||
repo2 = EntityRepository(session_maker, project_id=project2.id)
|
||||
|
||||
# Create first entity in project1
|
||||
entity1 = Entity(
|
||||
project_id=project1.id,
|
||||
title="Original Entity",
|
||||
entity_type="note",
|
||||
permalink="test/conflict-permalink",
|
||||
file_path="test/original.md",
|
||||
content_type="text/markdown",
|
||||
created_at=datetime.now(timezone.utc),
|
||||
updated_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
result1 = await repo1.upsert_entity(entity1)
|
||||
assert result1.permalink == "test/conflict-permalink"
|
||||
|
||||
# Create entity with same permalink in project2 (should NOT get suffix)
|
||||
entity2 = Entity(
|
||||
project_id=project2.id,
|
||||
title="Cross-Project Entity",
|
||||
entity_type="note",
|
||||
permalink="test/conflict-permalink", # Same permalink, different project
|
||||
file_path="test/cross-project.md",
|
||||
content_type="text/markdown",
|
||||
created_at=datetime.now(timezone.utc),
|
||||
updated_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
result2 = await repo2.upsert_entity(entity2)
|
||||
# Should keep original permalink (no suffix) since it's in a different project
|
||||
assert result2.permalink == "test/conflict-permalink"
|
||||
|
||||
# Now create entity with same permalink in project1 (should get suffix)
|
||||
entity3 = Entity(
|
||||
project_id=project1.id,
|
||||
title="Conflict Entity",
|
||||
entity_type="note",
|
||||
permalink="test/conflict-permalink", # Same permalink, same project
|
||||
file_path="test/conflict.md",
|
||||
content_type="text/markdown",
|
||||
created_at=datetime.now(timezone.utc),
|
||||
updated_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
result3 = await repo1.upsert_entity(entity3)
|
||||
# Should get suffix since it conflicts within the same project
|
||||
assert result3.permalink == "test/conflict-permalink-1"
|
||||
|
||||
# Verify all entities exist correctly
|
||||
assert result1.id != result2.id != result3.id
|
||||
assert result1.project_id == project1.id
|
||||
assert result2.project_id == project2.id
|
||||
assert result3.project_id == project1.id
|
||||
|
||||
@@ -329,6 +329,36 @@ class TestSearchTermPreparation:
|
||||
== "(hello AND world) OR test"
|
||||
)
|
||||
|
||||
def test_hyphenated_terms_with_boolean_operators(self, search_repository):
|
||||
"""Hyphenated terms with Boolean operators should be properly quoted."""
|
||||
# Test the specific case from the GitHub issue
|
||||
result = search_repository._prepare_search_term("tier1-test AND unicode")
|
||||
assert result == '"tier1-test" AND unicode'
|
||||
|
||||
# Test other hyphenated Boolean combinations
|
||||
assert (
|
||||
search_repository._prepare_search_term("multi-word OR single")
|
||||
== '"multi-word" OR single'
|
||||
)
|
||||
assert (
|
||||
search_repository._prepare_search_term("well-formed NOT badly-formed")
|
||||
== '"well-formed" NOT "badly-formed"'
|
||||
)
|
||||
assert (
|
||||
search_repository._prepare_search_term("test-case AND (hello OR world)")
|
||||
== '"test-case" AND (hello OR world)'
|
||||
)
|
||||
|
||||
# Test mixed special characters with Boolean operators
|
||||
assert (
|
||||
search_repository._prepare_search_term("config.json AND test-file")
|
||||
== '"config.json" AND "test-file"'
|
||||
)
|
||||
assert (
|
||||
search_repository._prepare_search_term("C++ OR python-script")
|
||||
== '"C++" OR "python-script"'
|
||||
)
|
||||
|
||||
def test_programming_terms_should_work(self, search_repository):
|
||||
"""Programming-related terms with special chars should be searchable."""
|
||||
# These should be quoted to handle special characters safely
|
||||
@@ -517,3 +547,53 @@ class TestSearchTermPreparation:
|
||||
# Test whitespace-only search
|
||||
results_whitespace = await search_repository.search(search_text=" ")
|
||||
assert isinstance(results_whitespace, list) # Should not crash
|
||||
|
||||
def test_boolean_query_empty_parts_coverage(self, search_repository):
|
||||
"""Test Boolean query parsing with empty parts (line 143 coverage)."""
|
||||
# Create queries that will result in empty parts after splitting
|
||||
result1 = search_repository._prepare_boolean_query(
|
||||
"hello AND AND world"
|
||||
) # Double operator
|
||||
assert "hello" in result1 and "world" in result1
|
||||
|
||||
result2 = search_repository._prepare_boolean_query(" OR test") # Leading operator
|
||||
assert "test" in result2
|
||||
|
||||
result3 = search_repository._prepare_boolean_query("test OR ") # Trailing operator
|
||||
assert "test" in result3
|
||||
|
||||
def test_parenthetical_term_quote_escaping(self, search_repository):
|
||||
"""Test quote escaping in parenthetical terms (lines 190-191 coverage)."""
|
||||
# Test term with quotes that needs escaping
|
||||
result = search_repository._prepare_parenthetical_term('(say "hello" world)')
|
||||
# Should escape quotes by doubling them
|
||||
assert '""hello""' in result
|
||||
|
||||
# Test term with single quotes
|
||||
result2 = search_repository._prepare_parenthetical_term("(it's working)")
|
||||
assert "it's working" in result2
|
||||
|
||||
def test_needs_quoting_empty_input(self, search_repository):
|
||||
"""Test _needs_quoting with empty inputs (line 207 coverage)."""
|
||||
# Test empty string
|
||||
assert not search_repository._needs_quoting("")
|
||||
|
||||
# Test whitespace-only string
|
||||
assert not search_repository._needs_quoting(" ")
|
||||
|
||||
# Test None-like cases
|
||||
assert not search_repository._needs_quoting("\t")
|
||||
|
||||
def test_prepare_single_term_empty_input(self, search_repository):
|
||||
"""Test _prepare_single_term with empty inputs (line 227 coverage)."""
|
||||
# Test empty string
|
||||
result1 = search_repository._prepare_single_term("")
|
||||
assert result1 == ""
|
||||
|
||||
# Test whitespace-only string
|
||||
result2 = search_repository._prepare_single_term(" ")
|
||||
assert result2 == " " # Should return as-is
|
||||
|
||||
# Test string that becomes empty after strip
|
||||
result3 = search_repository._prepare_single_term("\t\n")
|
||||
assert result3 == "\t\n" # Should return original
|
||||
|
||||
@@ -127,6 +127,36 @@ def test_entity_out_from_attributes():
|
||||
assert len(entity.relations) == 1
|
||||
|
||||
|
||||
def test_entity_response_with_none_permalink():
|
||||
"""Test EntityResponse can handle None permalink (fixes issue #170).
|
||||
|
||||
This test ensures that EntityResponse properly validates when the permalink
|
||||
field is None, which can occur when markdown files don't have explicit
|
||||
permalinks in their frontmatter during edit operations.
|
||||
"""
|
||||
# Simulate database model attributes with None permalink
|
||||
db_data = {
|
||||
"title": "Test Entity",
|
||||
"permalink": None, # This should not cause validation errors
|
||||
"file_path": "test/test-entity.md",
|
||||
"entity_type": "note",
|
||||
"content_type": "text/markdown",
|
||||
"observations": [],
|
||||
"relations": [],
|
||||
"created_at": "2023-01-01T00:00:00",
|
||||
"updated_at": "2023-01-01T00:00:00",
|
||||
}
|
||||
|
||||
# This should not raise a ValidationError
|
||||
entity = EntityResponse.model_validate(db_data)
|
||||
assert entity.permalink is None
|
||||
assert entity.title == "Test Entity"
|
||||
assert entity.file_path == "test/test-entity.md"
|
||||
assert entity.entity_type == "note"
|
||||
assert len(entity.observations) == 0
|
||||
assert len(entity.relations) == 0
|
||||
|
||||
|
||||
def test_search_nodes_input():
|
||||
"""Test SearchNodesInput validation."""
|
||||
search = SearchNodesRequest.model_validate({"query": "test query"})
|
||||
|
||||
@@ -1728,3 +1728,69 @@ async def test_move_entity_with_complex_observations(
|
||||
assert "Branch Strategy" in relation_targets
|
||||
assert "Multiple" in relation_targets
|
||||
assert "Links" in relation_targets
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_move_entity_with_null_permalink_generates_permalink(
|
||||
entity_service: EntityService,
|
||||
project_config: ProjectConfig,
|
||||
entity_repository: EntityRepository,
|
||||
):
|
||||
"""Test that moving entity with null permalink generates a new permalink automatically.
|
||||
|
||||
This tests the fix for issue #155 where entities with null permalinks from the database
|
||||
migration would fail validation when being moved. The fix ensures that entities with
|
||||
null permalinks get a generated permalink during move operations, regardless of the
|
||||
update_permalinks_on_move setting.
|
||||
"""
|
||||
# Create entity through direct database insertion to simulate migrated entity with null permalink
|
||||
from datetime import datetime, timezone
|
||||
|
||||
# Create an entity with null permalink directly in database (simulating migrated data)
|
||||
entity_data = {
|
||||
"title": "Test Entity",
|
||||
"file_path": "test/null-permalink-entity.md",
|
||||
"entity_type": "note",
|
||||
"content_type": "text/markdown",
|
||||
"permalink": None, # This is the key - null permalink from migration
|
||||
"created_at": datetime.now(timezone.utc),
|
||||
"updated_at": datetime.now(timezone.utc),
|
||||
}
|
||||
|
||||
# Create the entity directly in database
|
||||
created_entity = await entity_repository.create(entity_data)
|
||||
assert created_entity.permalink is None
|
||||
|
||||
# Create the physical file
|
||||
file_path = project_config.home / created_entity.file_path
|
||||
file_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
file_path.write_text("# Test Entity\n\nContent here.")
|
||||
|
||||
# Configure move without permalink updates (the default setting that previously triggered the bug)
|
||||
app_config = BasicMemoryConfig(update_permalinks_on_move=False)
|
||||
|
||||
# Move entity - this should now succeed and generate a permalink
|
||||
moved_entity = await entity_service.move_entity(
|
||||
identifier=created_entity.title, # Use title since permalink is None
|
||||
destination_path="moved/test-entity.md",
|
||||
project_config=project_config,
|
||||
app_config=app_config,
|
||||
)
|
||||
|
||||
# Verify the move succeeded and a permalink was generated
|
||||
assert moved_entity is not None
|
||||
assert moved_entity.file_path == "moved/test-entity.md"
|
||||
assert moved_entity.permalink is not None
|
||||
assert moved_entity.permalink != ""
|
||||
|
||||
# Verify the moved entity can be used to create an EntityResponse without validation errors
|
||||
from basic_memory.schemas.response import EntityResponse
|
||||
|
||||
response = EntityResponse.model_validate(moved_entity)
|
||||
assert response.permalink == moved_entity.permalink
|
||||
|
||||
# Verify the physical file was moved
|
||||
old_path = project_config.home / "test/null-permalink-entity.md"
|
||||
new_path = project_config.home / "moved/test-entity.md"
|
||||
assert not old_path.exists()
|
||||
assert new_path.exists()
|
||||
|
||||
@@ -17,6 +17,9 @@ def test_sync_tracker_initial_state(sync_tracker):
|
||||
assert sync_tracker.global_status == SyncStatus.IDLE
|
||||
assert sync_tracker.get_summary() == "✅ System ready"
|
||||
|
||||
# Test project-specific ready check for unknown project
|
||||
assert sync_tracker.is_project_ready("unknown-project")
|
||||
|
||||
|
||||
def test_start_project_sync(sync_tracker):
|
||||
"""Test starting project sync."""
|
||||
@@ -211,3 +214,49 @@ def test_summary_without_file_counts(sync_tracker):
|
||||
summary = sync_tracker.get_summary()
|
||||
assert "🔄 Syncing 2 projects" in summary
|
||||
assert "files" not in summary # Should not show file progress
|
||||
|
||||
|
||||
def test_is_project_ready_functionality(sync_tracker):
|
||||
"""Test project-specific ready checks."""
|
||||
# Unknown project should be ready
|
||||
assert sync_tracker.is_project_ready("unknown-project")
|
||||
|
||||
# Project in different states
|
||||
sync_tracker.start_project_sync("scanning-project")
|
||||
assert not sync_tracker.is_project_ready("scanning-project") # SCANNING = not ready
|
||||
|
||||
sync_tracker.update_project_progress("scanning-project", SyncStatus.SYNCING, "Processing")
|
||||
assert not sync_tracker.is_project_ready("scanning-project") # SYNCING = not ready
|
||||
|
||||
sync_tracker.fail_project_sync("scanning-project", "Test error")
|
||||
assert not sync_tracker.is_project_ready("scanning-project") # FAILED = not ready
|
||||
|
||||
sync_tracker.complete_project_sync("scanning-project")
|
||||
assert sync_tracker.is_project_ready("scanning-project") # COMPLETED = ready
|
||||
|
||||
# Test watching project
|
||||
sync_tracker.start_project_watch("watching-project")
|
||||
assert sync_tracker.is_project_ready("watching-project") # WATCHING = ready
|
||||
|
||||
|
||||
def test_project_isolation_scenario(sync_tracker):
|
||||
"""Test the specific bug scenario: project isolation with mixed sync states."""
|
||||
# Set up the bug scenario: one failed project, one healthy project
|
||||
sync_tracker.start_project_sync("main")
|
||||
sync_tracker.fail_project_sync(
|
||||
"main", "UNIQUE constraint failed: entity.file_path, entity.project_id"
|
||||
)
|
||||
|
||||
sync_tracker.start_project_sync("basic-memory-testing-20250626-1009")
|
||||
sync_tracker.complete_project_sync("basic-memory-testing-20250626-1009")
|
||||
sync_tracker.start_project_watch("basic-memory-testing-20250626-1009")
|
||||
|
||||
# Global status should be failed due to "main" project
|
||||
assert sync_tracker.global_status == SyncStatus.FAILED
|
||||
assert not sync_tracker.is_ready
|
||||
|
||||
# But the healthy project should be ready for operations
|
||||
assert sync_tracker.is_project_ready("basic-memory-testing-20250626-1009")
|
||||
assert not sync_tracker.is_project_ready("main")
|
||||
|
||||
# This demonstrates the fix: project-specific checks allow isolation
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Test configuration management."""
|
||||
|
||||
from basic_memory.config import BasicMemoryConfig
|
||||
|
||||
|
||||
class TestBasicMemoryConfig:
|
||||
"""Test BasicMemoryConfig behavior with BASIC_MEMORY_HOME environment variable."""
|
||||
|
||||
def test_default_behavior_without_basic_memory_home(self, config_home, monkeypatch):
|
||||
"""Test that config uses default path when BASIC_MEMORY_HOME is not set."""
|
||||
# Ensure BASIC_MEMORY_HOME is not set
|
||||
monkeypatch.delenv("BASIC_MEMORY_HOME", raising=False)
|
||||
|
||||
config = BasicMemoryConfig()
|
||||
|
||||
# Should use the default path (home/basic-memory)
|
||||
expected_path = str(config_home / "basic-memory")
|
||||
assert config.projects["main"] == expected_path
|
||||
|
||||
def test_respects_basic_memory_home_environment_variable(self, config_home, monkeypatch):
|
||||
"""Test that config respects BASIC_MEMORY_HOME environment variable."""
|
||||
custom_path = str(config_home / "app" / "data")
|
||||
monkeypatch.setenv("BASIC_MEMORY_HOME", custom_path)
|
||||
|
||||
config = BasicMemoryConfig()
|
||||
|
||||
# Should use the custom path from environment variable
|
||||
assert config.projects["main"] == custom_path
|
||||
|
||||
def test_model_post_init_respects_basic_memory_home(self, config_home, monkeypatch):
|
||||
"""Test that model_post_init creates main project with BASIC_MEMORY_HOME when missing."""
|
||||
custom_path = str(config_home / "custom" / "memory" / "path")
|
||||
monkeypatch.setenv("BASIC_MEMORY_HOME", custom_path)
|
||||
|
||||
# Create config without main project
|
||||
other_path = str(config_home / "some" / "path")
|
||||
config = BasicMemoryConfig(projects={"other": other_path})
|
||||
|
||||
# model_post_init should have added main project with BASIC_MEMORY_HOME
|
||||
assert "main" in config.projects
|
||||
assert config.projects["main"] == custom_path
|
||||
|
||||
def test_model_post_init_fallback_without_basic_memory_home(self, config_home, monkeypatch):
|
||||
"""Test that model_post_init falls back to default when BASIC_MEMORY_HOME is not set."""
|
||||
# Ensure BASIC_MEMORY_HOME is not set
|
||||
monkeypatch.delenv("BASIC_MEMORY_HOME", raising=False)
|
||||
|
||||
# Create config without main project
|
||||
other_path = str(config_home / "some" / "path")
|
||||
config = BasicMemoryConfig(projects={"other": other_path})
|
||||
|
||||
# model_post_init should have added main project with default path
|
||||
expected_path = str(config_home / "basic-memory")
|
||||
assert "main" in config.projects
|
||||
assert config.projects["main"] == expected_path
|
||||
|
||||
def test_basic_memory_home_with_relative_path(self, config_home, monkeypatch):
|
||||
"""Test that BASIC_MEMORY_HOME works with relative paths."""
|
||||
relative_path = "relative/memory/path"
|
||||
monkeypatch.setenv("BASIC_MEMORY_HOME", relative_path)
|
||||
|
||||
config = BasicMemoryConfig()
|
||||
|
||||
# Should use the exact value from environment variable
|
||||
assert config.projects["main"] == relative_path
|
||||
|
||||
def test_basic_memory_home_overrides_existing_main_project(self, config_home, monkeypatch):
|
||||
"""Test that BASIC_MEMORY_HOME is not used when a map is passed in the constructor."""
|
||||
custom_path = str(config_home / "override" / "memory" / "path")
|
||||
monkeypatch.setenv("BASIC_MEMORY_HOME", custom_path)
|
||||
|
||||
# Try to create config with a different main project path
|
||||
original_path = str(config_home / "original" / "path")
|
||||
config = BasicMemoryConfig(projects={"main": original_path})
|
||||
|
||||
# The default_factory should override with BASIC_MEMORY_HOME value
|
||||
# Note: This tests the current behavior where default_factory takes precedence
|
||||
assert config.projects["main"] == original_path
|
||||
@@ -121,7 +121,7 @@ requires-dist = [
|
||||
{ name = "alembic", specifier = ">=1.14.1" },
|
||||
{ name = "dateparser", specifier = ">=1.2.0" },
|
||||
{ name = "fastapi", extras = ["standard"], specifier = ">=0.115.8" },
|
||||
{ name = "fastmcp", specifier = ">=2.3.4" },
|
||||
{ name = "fastmcp", specifier = ">=2.3.4,<2.10.0" },
|
||||
{ name = "greenlet", specifier = ">=3.1.1" },
|
||||
{ name = "icecream", specifier = ">=2.1.3" },
|
||||
{ name = "loguru", specifier = ">=0.7.3" },
|
||||
|
||||
Reference in New Issue
Block a user