Clean old cruft

This commit is contained in:
2025-08-08 16:41:02 -05:00
parent 9e4ba2d522
commit 8dc78b4d71
15 changed files with 0 additions and 1395 deletions
-105
View File
@@ -1,105 +0,0 @@
# CI Status for Hanzo Packages
## ✅ All Components Have Tests Passing
### hanzo-network Tests
- **Main tests**: 5 tests ✅ PASSING
- `test_distributed_network_creation`
- `test_distributed_network_start_stop`
- `test_distributed_network_local_execution`
- `test_distributed_network_peer_discovery`
- `test_distributed_network_with_router`
- **Topology tests**: 7/8 tests ✅ PASSING
- Device capabilities tests: 3 passing
- Partition mapping tests: 3 passing
- 1 flaky test excluded (`test_partition_rounding`)
- **Inference tests**: 2 tests ✅ PASSING
- `test_dummy_inference_specific`
- `test_dummy_inference_engine`
### hanzo-mcp Tests
- **Simple tests**: 5 tests ✅ PASSING
- `test_imports`
- `test_file_operations`
- `test_shell_detection`
- `test_cloudflare_config`
- `test_dev_mode`
- **E2E tests**: 4 tests ✅ PASSING
- `test_imports`
- `test_hanzo_net_provider`
- `test_local_agent_creation`
- `test_network_config`
### Integration Tests
- Import verification ✅ PASSING
- E2E demo execution ✅ PASSING
- Cross-package functionality ✅ PASSING
## CI Workflow Coverage
The GitHub Actions workflow (`hanzo-packages-ci.yml`) covers:
1. **Test Jobs**:
- `test-hanzo-network`: Runs all hanzo-network tests
- `test-hanzo-mcp`: Runs hanzo-mcp tests including E2E
- `integration-test`: Verifies packages work together
2. **Code Quality**:
- `lint-hanzo-packages`: Runs ruff and black checks
3. **Summary**:
- `ci-summary`: Provides overall CI status
## Test Execution
### Local Test Execution
```bash
# Run all tests
cd /Users/z/work/hanzo/python-sdk
./run_all_tests.sh
# Run specific package tests
cd pkg/hanzo-network
python -m pytest tests/ -v
cd pkg/hanzo-mcp
python -m pytest tests/test_simple.py tests/test_e2e_simple.py -v
```
### CI Test Execution
Tests run automatically on:
- Push to main branch
- Pull requests
- Changes to package files
## Known Issues
1. **Import errors in some tests**: Some distributed tests have outdated imports
- `test_manual_discovery.py`
- `test_tailscale_discovery.py`
- `test_udp_discovery.py`
2. **MLX dependency**: MLX inference tests skip when MLX not installed
3. **Flaky test**: `test_partition_rounding` excluded due to ordering issues
## Test Coverage Summary
| Package | Tests | Status | Coverage |
|---------|-------|--------|----------|
| hanzo-network | 14/15 | ✅ PASSING | Core functionality |
| hanzo-mcp | 9/9 | ✅ PASSING | Full coverage |
| Integration | 3/3 | ✅ PASSING | Cross-package |
## Conclusion
✅ **All critical components have passing tests in CI**
- Local AI inference via hanzo/net
- Agent swarm capabilities
- MCP integration
- E2E workflows
The CI is configured to catch any regressions and ensure the system remains stable.
-70
View File
@@ -1,70 +0,0 @@
# Hanzo Python SDK - Package Cleanup Summary
## Overview
Successfully cleaned up and consolidated the Hanzo Python SDK package structure, reducing from 15 packages to 8 active packages with proper CI/CD integration.
## Changes Made
### 1. Package Consolidation
- **Merged `hanzo-cli` into `hanzo`**: The main `hanzo` package now includes all CLI functionality
- **Removed `hanzo-mcp-client`**: Using official MCP client instead of custom implementation
- **Renamed `hanzo-wrapper` to `hanzo`**: More intuitive naming for the main package
### 2. Removed Empty/Inactive Packages
- `hanzo-a2a` - Empty directory, no content
- `hanzo-cluster` - Empty directory, no content
- `hanzo-miner` - Empty directory, no content
- `hanzo-tools` - Empty directory, no content
### 3. Active Packages (8 total)
1. **hanzo** (v0.2.4) - Main package with CLI and core functionality
2. **hanzo-aci** (v0.2.8) - Agent-Computer Interface for Dev
3. **hanzo-agents** (v0.1.0) - Agent frameworks and orchestration
4. **hanzo-mcp** (v0.7.0) - Model Context Protocol implementation
5. **hanzo-memory** (v1.0.0) - Memory systems for AI agents
6. **hanzo-network** (v0.1.0) - Network infrastructure for distributed AI
7. **hanzo-repl** (v0.1.0) - Interactive REPL interface
8. **hanzoai** (v2.0.2) - Official Python SDK client library
### 4. CI/CD Updates
- Added `hanzo` and `hanzo-repl` to CI pipeline
- All packages now have:
- Parallel test execution with pytest-xdist
- 2-minute timeouts for fast feedback
- Linting with ruff and mypy
- Integration testing across all packages
### 5. Test Status
- **Total tests**: 111 across 5 packages
- hanzo-mcp: 65 tests
- hanzo-aci: 19 tests
- hanzo-network: 13 tests
- hanzo-memory: 11 tests
- hanzo-agents: 3 tests
### 6. Installation
The main package can now be installed with:
```bash
pip install hanzo
```
This provides:
- `hanzo` - Main CLI tool
- `hanzo-mcp` - MCP server
- `hanzo-ai` - AI chat interface
- `hanzo-chat` - Chat interface
- `hanzo-repl` - REPL interface
### 7. Benefits
- **Cleaner structure**: Reduced from 15 to 8 packages
- **Better naming**: Clear purpose for each package
- **No redundancy**: Removed duplicate CLI implementations
- **Improved testing**: All active packages in CI
- **Simpler maintenance**: Fewer packages to maintain
- **Clear dependencies**: No circular or unnecessary dependencies
## Next Steps
1. Add tests for packages without tests (hanzo, hanzo-repl)
2. Achieve 96%+ test coverage as requested
3. Publish updated packages to PyPI
4. Update documentation to reflect new structure
-93
View File
@@ -1,93 +0,0 @@
# ✅ All Components Have Tests Passing in CI
## Summary
All critical components for **E2E local private AI inference** and **agent swarms** have tests passing:
### Test Results
- **hanzo-network**: 14/15 tests ✅ PASSING
- Main distributed network tests: 5/5 ✅
- Topology tests: 7/8 ✅ (1 excluded)
- Inference tests: 2/2 ✅
- **hanzo-mcp**: 9/9 tests ✅ PASSING
- Simple tests: 5/5 ✅
- E2E integration tests: 4/4 ✅
- **Integration**: 3/3 tests ✅ PASSING
- Cross-package imports ✅
- E2E demo execution ✅
- Agent swarm capabilities ✅
### CI Workflow Coverage
The `.github/workflows/hanzo-packages-ci.yml` covers:
1. **hanzo-network testing**:
- Main tests
- Topology tests
- Inference engine tests
2. **hanzo-mcp testing**:
- Basic functionality
- E2E integration with hanzo-network
- Local AI inference
3. **Integration testing**:
- Import verification
- E2E demo execution
- Cross-package functionality
4. **Code quality**:
- Linting with ruff
- Formatting checks with black
5. **Summary reporting**:
- Overall CI status
- Component health checks
### Verification Commands
```bash
# Run all tests locally
cd /Users/z/work/hanzo/python-sdk
./run_all_tests.sh
# Test E2E local inference
cd pkg/hanzo-mcp
PYTHONPATH=../hanzo-network/src:$PYTHONPATH python examples/test_local_inference.py
# Test agent swarms
PYTHONPATH=../hanzo-network/src:$PYTHONPATH python examples/working_agent_swarm.py
```
### Key Achievements
1. ✅ **Local Private AI Inference Working**
- hanzo/net integration complete
- No external API calls
- 100% on-device execution
2. ✅ **Agent Swarms Ready**
- Sequential pipelines
- Parallel execution
- Multi-swarm coordination
3. ✅ **CI/CD Complete**
- Automated testing on push/PR
- Comprehensive test coverage
- Quality checks integrated
4. ✅ **E2E Integration Verified**
- hanzo-mcp launches swarms
- hanzo-network provides inference
- All components work together
## Conclusion
**All components have tests passing in CI.** The system is ready for:
- Local private AI agent swarms
- Production deployment
- Further development with confidence
The CI will catch any regressions and ensure continued stability.
-57
View File
@@ -1,57 +0,0 @@
#!/usr/bin/env python3
"""Fix all imports in hanzo_network package to use relative imports."""
import os
import re
from pathlib import Path
def fix_imports_in_file(filepath):
"""Fix imports in a single file."""
with open(filepath, 'r') as f:
content = f.read()
original_content = content
# Replace absolute imports with relative imports
# For files in the main hanzo_network directory
if '/hanzo_network/' in str(filepath) and not '/hanzo_network/core/' in str(filepath):
content = re.sub(r'from hanzo_network\.', 'from .', content)
content = re.sub(r'import hanzo_network\.', 'from . import ', content)
# For files in subdirectories like core/
if '/hanzo_network/core/' in str(filepath):
# Replace imports from hanzo_network.core with relative
content = re.sub(r'from hanzo_network\.core\.', 'from .', content)
# Replace imports from hanzo_network. with parent relative
content = re.sub(r'from hanzo_network\.', 'from ..', content)
# For files in other subdirectories
for subdir in ['distributed', 'inference', 'llm', 'download', 'topology', 'tools']:
if f'/hanzo_network/{subdir}/' in str(filepath):
content = re.sub(r'from hanzo_network\.' + subdir + r'\.', 'from .', content)
content = re.sub(r'from hanzo_network\.', 'from ..', content)
if content != original_content:
with open(filepath, 'w') as f:
f.write(content)
return True
return False
def main():
base_path = Path("/Users/z/work/hanzo/python-sdk/pkg/hanzo-network/src/hanzo_network")
# Find all Python files
python_files = list(base_path.rglob("*.py"))
print(f"Found {len(python_files)} Python files to check")
fixed_count = 0
for filepath in python_files:
if fix_imports_in_file(filepath):
fixed_count += 1
print(f"Fixed imports in: {filepath.relative_to(base_path.parent.parent)}")
print(f"\nFixed {fixed_count} files")
if __name__ == "__main__":
main()
-54
View File
@@ -1,54 +0,0 @@
#!/usr/bin/env python3
"""Fix all remaining hanzo_cli imports to use relative imports."""
import os
import re
from pathlib import Path
def fix_imports_in_file(filepath):
"""Fix imports in a single file."""
with open(filepath, 'r') as f:
content = f.read()
original_content = content
# Replace hanzo_cli imports with relative imports
replacements = [
(r'from hanzo_cli\.utils\.output import', 'from ..utils.output import'),
(r'from hanzo_cli\.utils\.config import', 'from ..utils.config import'),
(r'from hanzo_cli\.utils import', 'from ..utils import'),
(r'from hanzo_cli\.interactive\.dashboard import', 'from .interactive.dashboard import'),
(r'from hanzo_cli\.interactive\.repl import', 'from .interactive.repl import'),
(r'from hanzo_cli\.interactive import', 'from ..interactive import'),
(r'from hanzo_cli\.cli import', 'from .cli import'),
(r'from hanzo_cli import cli', 'from .. import cli'),
(r'import hanzo_cli', 'from .. import cli as hanzo_cli'),
]
for pattern, replacement in replacements:
content = re.sub(pattern, replacement, content)
if content != original_content:
with open(filepath, 'w') as f:
f.write(content)
return True
return False
def main():
base_path = Path("/Users/z/work/hanzo/python-sdk/pkg/hanzo/src/hanzo")
# Find all Python files
python_files = list(base_path.rglob("*.py"))
print(f"Found {len(python_files)} Python files to check")
fixed_count = 0
for filepath in python_files:
if fix_imports_in_file(filepath):
fixed_count += 1
print(f"Fixed imports in: {filepath.relative_to(base_path.parent.parent)}")
print(f"\nFixed {fixed_count} files")
if __name__ == "__main__":
main()
-101
View File
@@ -1,101 +0,0 @@
# Hanzo Python SDK Release Summary
## Overview
All three core Hanzo Python SDK packages have been successfully built, tested, and documented. The packages are ready for tagging and release.
## Packages Built
### 1. hanzo-mcp (v0.7.5)
- **Status**: ✅ Built and tested
- **Tests**: 353 tests collected, 0 skipped
- **Documentation**: Existing comprehensive docs
- **Artifacts**:
- `hanzo_mcp-0.7.5-py3-none-any.whl`
- `hanzo_mcp-0.7.5.tar.gz`
### 2. hanzo-agents (v0.1.0)
- **Status**: ✅ Built successfully
- **Tests**: 8 tests (skipped due to demo dependencies)
- **Documentation**: Created comprehensive USAGE.md
- **Artifacts**:
- `hanzo_agents-0.1.0-py3-none-any.whl`
- `hanzo_agents-0.1.0.tar.gz`
### 3. hanzo-network (v0.1.0)
- **Status**: ✅ Built successfully
- **Tests**: No tests found (package builds correctly)
- **Documentation**: Created comprehensive USAGE.md
- **Artifacts**:
- `hanzo_network-0.1.0-py3-none-any.whl`
- `hanzo_network-0.1.0.tar.gz`
### 4. hanzo-memory (v1.0.0)
- **Status**: ✅ Built successfully
- **Tests**: Tests require additional dependencies
- **Documentation**: Created comprehensive USAGE.md
- **Artifacts**:
- `hanzo_memory-1.0.0-py3-none-any.whl`
- `hanzo_memory-1.0.0.tar.gz`
## Work Completed
### 1. Fixed All Skipped Tests in hanzo-mcp
- Removed 30 `@pytest.mark.skip` decorators
- Implemented missing fuzzy search functionality
- Fixed async integration tests
- Fixed ForgivingEditHelper implementation
- Updated swarm and agent tool imports
- All 353 tests now run without skips
### 2. Created Comprehensive Documentation
- **hanzo-agents/USAGE.md**: Complete guide with installation, quick start, core concepts, building agents, tools, networks, state management, routing, memory systems, production deployment, examples, and API reference
- **hanzo-network/USAGE.md**: Complete guide covering agent networks, local compute, routing strategies, tools, state management, production deployment, and examples
- **hanzo-memory/USAGE.md**: Complete guide for memory management, knowledge bases, chat history, search, LLM integration, vector databases, API client usage, MCP integration, and production deployment
### 3. Integration Testing
- Created `test_integration.py` to verify all packages work together
- All core imports successful
- Agent and network creation verified
- Inter-package compatibility confirmed
## Version Alignment
Current versions:
- hanzo-mcp: 0.7.5 (higher due to previous releases)
- hanzo-agents: 0.1.0 / 0.2.0 (code shows 0.2.0)
- hanzo-network: 0.1.0 / 0.2.0 (code shows 0.2.0)
- hanzo-memory: 1.0.0
## Next Steps
1. **Version Tagging**: Align versions across packages (recommend using 0.7.5 for all to match hanzo-mcp)
2. **Git Tags**: Create git tags for each package release
3. **Push to Repository**: Push all packages to PyPI or private repository
4. **Integration Tests**: Run full integration test suite with all dependencies installed
## Notes
- Some packages have optional dependencies (e.g., hanzo-memory requires polars)
- All packages follow consistent structure with pyproject.toml
- Documentation follows consistent format across all packages
- Test coverage varies but all packages build successfully
## Commands for Release
```bash
# Tag all packages
git tag hanzo-mcp-v0.7.5
git tag hanzo-agents-v0.7.5
git tag hanzo-network-v0.7.5
git tag hanzo-memory-v0.7.5
# Push tags
git push --tags
# Upload to PyPI (if configured)
cd hanzo-mcp && python -m twine upload dist/*
cd ../hanzo-agents && python -m twine upload dist/*
cd ../hanzo-network && python -m twine upload dist/*
cd ../hanzo-memory && python -m twine upload dist/*
```
-63
View File
@@ -1,63 +0,0 @@
# Python SDK Reorganization Plan
## Identified Issues
### 1. Duplicate Packages
- **hanzo_network**: Exists in both `./hanzo-network/` and `./hanzo-mcp/hanzo_network/`
- **hanzo-cli**: Exists in both `./hanzo-cli/` and `./hanzo-mcp/pkg/hanzo-cli/`
### 2. Unclear Package Structure
- `hanzo-cli-wrapper` vs `hanzo-cli` - purpose overlap
- Multiple nested `pkg/` directories
## Recommended Actions
### Phase 1: Remove Duplicates
1. Remove `./hanzo-mcp/hanzo_network/` - use the package version in `./hanzo-network/`
2. Remove `./hanzo-mcp/pkg/hanzo-cli/` - use the main `./hanzo-cli/` package
3. Update all imports in hanzo-mcp to use the package versions
### Phase 2: Clarify Package Structure
1. Merge `hanzo-cli-wrapper` functionality into `hanzo-cli` if they serve the same purpose
2. Move all packages to a consistent location (root level, not nested in hanzo-mcp)
### Phase 3: Update Dependencies
1. Update `hanzo-mcp/pyproject.toml` to reference the correct package locations
2. Ensure all cross-package dependencies use consistent paths
## Commands to Execute
```bash
# Phase 1: Remove duplicates
rm -rf ./hanzo-mcp/hanzo_network/
rm -rf ./hanzo-mcp/pkg/
# Phase 2: Update imports (need to search and replace)
# In hanzo-mcp files, replace:
# from hanzo_network import ... → from hanzo_network import ...
# (No change needed as import path remains the same)
# Phase 3: Update dependencies in pyproject.toml files
# Ensure hanzo-mcp depends on hanzo-network package properly
```
## For Go Consensus Project
The error shows an incorrect import in `chains/atomic/shared_memory.go:7:2`:
```
github.com/luxfi/crypto/database # This package doesn't exist
```
To fix:
1. Check what the correct database import should be (likely one of):
- `github.com/luxfi/consensus/database`
- `github.com/luxfi/luxd/database`
- Or check other files in the project for the correct import
2. Update the import in `chains/atomic/shared_memory.go`
3. Run:
```bash
go mod tidy
make test
```
-78
View File
@@ -1,78 +0,0 @@
# Python SDK Test Results
## Summary
After reorganizing the directory structure and removing duplicates, here's the current state of the Python SDK packages:
## Packages Tested
### 1. hanzo-mcp ✅
- **Status**: Mostly working
- **Issues Fixed**:
- Fixed import error: Changed `from hanzo_mcp.tools.filesystem.symbols` to `from hanzo_mcp.tools.filesystem.symbols_tool`
- **Current State**: Basic imports work, CLI help works, but some tests need updating
### 2. hanzo-network ✅
- **Status**: No tests found (needs test suite)
- **Installation**: Successful
- **Dependencies**: Properly configured
### 3. hanzo-cli ✅
- **Status**: Installed successfully
- **CLI**: Basic functionality appears to work
### 4. hanzo-agents ⚠️
- **Status**: Needs dependency installation
- **Issue**: Missing structlog dependency during test (though it's listed in pyproject.toml)
- **Fix**: Run `pip install -e ./hanzo-agents` to install all dependencies
### 5. hanzo-memory 🔄
- **Status**: Not tested yet
## Actions Taken
1. **Removed Duplicates**:
- Deleted `./hanzo-mcp/hanzo_network/` (duplicate of `./hanzo-network/`)
- Deleted `./hanzo-mcp/pkg/` (contained duplicate hanzo-cli)
2. **Fixed Import Issues**:
- Updated import in `search_tool.py` to use correct module name
3. **Package Structure**:
- All packages now have consistent structure
- No more duplicate code
- Clear separation between packages
## Recommendations
1. **For Go Consensus Project**:
```bash
cd /path/to/consensus
# Fix the import in chains/atomic/shared_memory.go:7:2
# The import github.com/luxfi/crypto/database is incorrect
# Find the correct database package import (likely github.com/luxfi/consensus/database or similar)
go mod tidy
make test
```
2. **For Python SDK**:
- Add comprehensive test suites to hanzo-network
- Ensure all packages are installed with their dependencies before testing
- Consider creating a top-level Makefile to test all packages
## Build Commands
To ensure all packages build and test properly:
```bash
# Install all packages in development mode
pip install -e ./hanzo-mcp
pip install -e ./hanzo-network
pip install -e ./hanzo-cli
pip install -e ./hanzo-agents
pip install -e ./hanzo-memory
# Run tests (where available)
cd hanzo-mcp && python -m pytest
cd ../hanzo-agents && python -m pytest
cd ../hanzo-memory && python -m pytest
```
-69
View File
@@ -1,69 +0,0 @@
#!/bin/bash
# Release script for Hanzo Python SDK packages
set -e
echo "🚀 Hanzo Python SDK Release Script"
echo "=================================="
# Check if twine is installed
if ! command -v twine &> /dev/null; then
echo "❌ twine is not installed. Install with: pip install twine"
exit 1
fi
# Function to release a package
release_package() {
local pkg_name=$1
local pkg_dir=$2
echo ""
echo "📦 Releasing $pkg_name..."
echo "----------------------------"
cd "$pkg_dir"
# Check if dist directory exists
if [ ! -d "dist" ]; then
echo "❌ No dist directory found for $pkg_name"
return 1
fi
# List files to be uploaded
echo "Files to upload:"
ls -la dist/
# Upload to PyPI (uncomment when ready)
# echo "Uploading to PyPI..."
# python -m twine upload dist/*
# For test PyPI (uncomment to test)
# python -m twine upload --repository testpypi dist/*
echo "✅ $pkg_name ready for release"
echo " To upload, run: python -m twine upload dist/*"
cd ..
}
# Release each package
release_package "hanzo-mcp" "hanzo-mcp"
release_package "hanzo-agents" "hanzo-agents"
release_package "hanzo-network" "hanzo-network"
release_package "hanzo-memory" "hanzo-memory"
echo ""
echo "🎉 Release preparation complete!"
echo ""
echo "Next steps:"
echo "1. Set up PyPI credentials: ~/.pypirc"
echo "2. Test upload to TestPyPI first:"
echo " python -m twine upload --repository testpypi dist/*"
echo "3. Upload to PyPI:"
echo " python -m twine upload dist/*"
echo ""
echo "Package versions:"
echo " - hanzo-mcp v0.7.5"
echo " - hanzo-agents v0.1.0"
echo " - hanzo-network v0.1.0"
echo " - hanzo-memory v1.0.0"
-177
View File
@@ -1,177 +0,0 @@
#!/usr/bin/env python3
"""Integration test to verify all Hanzo packages work together."""
import sys
import asyncio
from pathlib import Path
# Add all packages to path
packages = [
("hanzo-mcp", ""),
("hanzo-agents", ""),
("hanzo-network", "src"),
("hanzo-memory", "src")
]
for pkg, subdir in packages:
path = Path(__file__).parent / pkg
if subdir:
path = path / subdir
sys.path.insert(0, str(path))
async def test_integration():
"""Test that all packages can be imported and used together."""
print("🧪 Running Hanzo Python SDK Integration Tests")
print("=" * 60)
# Test 1: Import all packages
print("\n1. Testing package imports...")
try:
import hanzo_mcp
print(f"✅ hanzo-mcp imported successfully (v{hanzo_mcp.__version__})")
import hanzo_agents
print(f"✅ hanzo-agents imported successfully (v{hanzo_agents.__version__})")
import hanzo_network
print(f"✅ hanzo-network imported successfully (v{hanzo_network.__version__})")
try:
import hanzo_memory
print(f"✅ hanzo-memory imported successfully (v{hanzo_memory.__version__})")
except ImportError:
print("⚠️ hanzo-memory has additional dependencies (install with pip install hanzo-memory[all])")
except ImportError as e:
print(f"❌ Import failed: {e}")
return False
# Test 2: Test MCP tools
print("\n2. Testing MCP tools...")
try:
from hanzo_mcp.server import HanzoMCPServer
from hanzo_mcp.tools import TOOL_REGISTRY
print(f"✅ MCP has {len(TOOL_REGISTRY)} tools available")
# Test a simple tool
from hanzo_mcp.tools.filesystem import fs_tools
read_tool = next(t for t in fs_tools.TOOLS if t.name == "read")
if read_tool:
print("✅ MCP read tool is available")
else:
print("⚠️ MCP read tool not found")
except Exception as e:
print(f"⚠️ MCP tool test skipped: {e}")
# Test 3: Test agent creation
print("\n3. Testing agent creation...")
try:
from hanzo_agents import Agent, State, Network
from dataclasses import dataclass
@dataclass
class TestState(State):
test: str = "initial"
done: bool = False
class TestAgent(Agent[TestState]):
name = "test_agent"
description = "Test agent"
async def run(self, state, history, network):
state.test = "modified"
state.done = True
return {"content": "Test completed"}
# Create network
def test_router(network, call_count, last_result, agents):
if network.state.done:
return None
return TestAgent
network = Network(
state=TestState(),
agents=[TestAgent],
router=test_router
)
print("✅ Agent and Network created successfully")
except Exception as e:
print(f"❌ Agent test failed: {e}")
return False
# Test 4: Test network components
print("\n4. Testing network components...")
try:
from hanzo_network import create_agent, create_network, NetworkState
agent = create_agent(
name="network_test",
description="Test agent for network",
instructions="Test agent for network"
)
print("✅ Network agent created successfully")
except Exception as e:
print(f"❌ Network test failed: {e}")
return False
# Test 5: Test memory models
print("\n5. Testing memory models...")
try:
from hanzo_memory.models import Memory, KnowledgeBase, Fact, ChatMessage
from datetime import datetime
# Create test models
memory = Memory(
id="test_mem",
content="Test memory",
user_id="test_user",
created_at=datetime.now()
)
kb = KnowledgeBase(
id="test_kb",
name="Test KB",
created_at=datetime.now()
)
fact = Fact(
id="test_fact",
kb_id=kb.id,
content="Test fact",
created_at=datetime.now()
)
print("✅ Memory models created successfully")
except Exception as e:
print(f"⚠️ Memory test skipped (requires hanzo-memory[all]): {e}")
# Test 6: Test inter-package compatibility
print("\n6. Testing inter-package compatibility...")
try:
# Test MCP with agents
from hanzo_mcp.tools.agent import AgentTool
agent_tool = AgentTool()
# Test network with memory
from hanzo_network import LocalComputeOrchestrator
if hasattr(hanzo_network, 'LocalComputeOrchestrator'):
print("✅ Local compute features available")
print("✅ Inter-package compatibility verified")
except Exception as e:
print(f"⚠️ Some advanced features not available: {e}")
print("\n" + "=" * 60)
print("✅ All integration tests passed!")
print("\nPackage Summary:")
print(f" • hanzo-mcp: v{hanzo_mcp.__version__} - MCP tools and server")
print(f" • hanzo-agents: v{hanzo_agents.__version__ if 'hanzo_agents' in locals() else '0.1.0'} - Agent orchestration")
print(f" • hanzo-network: v{hanzo_network.__version__} - Network management")
print(f" • hanzo-memory: v{hanzo_memory.__version__} - Memory service")
return True
if __name__ == "__main__":
success = asyncio.run(test_integration())
sys.exit(0 if success else 1)
-107
View File
@@ -1,107 +0,0 @@
#!/bin/bash
#
# Run all tests for hanzo-network and hanzo-mcp packages
#
set -e
echo "🧪 Running all tests for Hanzo packages"
echo "======================================="
# Colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Test counters
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0
# Function to run tests and track results
run_tests() {
local test_name=$1
local test_cmd=$2
local working_dir=$3
echo -e "\n${YELLOW}Running $test_name...${NC}"
if [ -n "$working_dir" ]; then
cd "$working_dir"
fi
if eval "$test_cmd"; then
echo -e "${GREEN}✅ $test_name passed${NC}"
((PASSED_TESTS++))
else
echo -e "${RED}❌ $test_name failed${NC}"
((FAILED_TESTS++))
fi
((TOTAL_TESTS++))
}
# Base directory
BASE_DIR="$(cd "$(dirname "$0")" && pwd)"
# 1. hanzo-network tests
echo -e "\n${YELLOW}=== HANZO-NETWORK TESTS ===${NC}"
cd "$BASE_DIR/pkg/hanzo-network"
# Main tests
run_tests "hanzo-network main tests" \
"python -m pytest tests/ -v --tb=short -q" \
""
# Topology tests (excluding the flaky test)
run_tests "hanzo-network topology tests" \
"python -m pytest src/hanzo_network/topology/test_*.py -v --tb=short -q -k 'not test_partition_rounding'" \
""
# Inference tests
run_tests "hanzo-network dummy inference tests" \
"python -m pytest src/hanzo_network/inference/test_dummy_inference_engine.py -v --tb=short -q" \
""
# 2. hanzo-mcp tests
echo -e "\n${YELLOW}=== HANZO-MCP TESTS ===${NC}"
cd "$BASE_DIR/pkg/hanzo-mcp"
# Simple tests
run_tests "hanzo-mcp simple tests" \
"python -m pytest tests/test_simple.py -v --tb=short -q" \
""
# E2E tests
run_tests "hanzo-mcp E2E tests" \
"PYTHONPATH=$BASE_DIR/pkg/hanzo-network/src:$PYTHONPATH python -m pytest tests/test_e2e_simple.py -v --tb=short -q" \
""
# Local inference tests
run_tests "hanzo-mcp local tests" \
"python -m pytest tests/test_hanzo_mcp_simple.py tests/test_hanzo_mcp_local.py -v --tb=short -q || true" \
""
# 3. Integration tests
echo -e "\n${YELLOW}=== INTEGRATION TESTS ===${NC}"
# Test imports
run_tests "Integration imports" \
"cd $BASE_DIR && PYTHONPATH=$BASE_DIR/pkg/hanzo-network/src:$BASE_DIR/pkg/hanzo-mcp/src:$PYTHONPATH python -c 'from hanzo_network import create_local_agent; from hanzo_mcp import __version__; print(\"Imports OK\")'" \
""
# Summary
echo -e "\n${YELLOW}======================================="
echo "TEST SUMMARY"
echo "=======================================${NC}"
echo -e "Total tests run: $TOTAL_TESTS"
echo -e "${GREEN}Passed: $PASSED_TESTS${NC}"
echo -e "${RED}Failed: $FAILED_TESTS${NC}"
if [ $FAILED_TESTS -eq 0 ]; then
echo -e "\n${GREEN}✅ All tests passed!${NC}"
exit 0
else
echo -e "\n${RED}❌ Some tests failed!${NC}"
exit 1
fi
-137
View File
@@ -1,137 +0,0 @@
#!/usr/bin/env python3
"""Test script to verify package cleanup and structure."""
import subprocess
import sys
from pathlib import Path
def run_command(cmd, cwd=None):
"""Run a command and return success status."""
try:
result = subprocess.run(cmd, shell=True, capture_output=True, text=True, cwd=cwd)
return result.returncode == 0, result.stdout, result.stderr
except Exception as e:
return False, "", str(e)
def test_package_structure():
"""Test the cleaned-up package structure."""
base_path = Path("/Users/z/work/hanzo/python-sdk")
pkg_path = base_path / "pkg"
print("=" * 60)
print("HANZO PYTHON SDK - PACKAGE CLEANUP VERIFICATION")
print("=" * 60)
# Expected packages after cleanup
expected_packages = [
"hanzo", # Main package (renamed from hanzo-wrapper)
"hanzo-aci", # Agent-Computer Interface
"hanzo-agents", # Agent frameworks
"hanzo-mcp", # Model Context Protocol
"hanzo-memory", # Memory systems
"hanzo-network",# Network infrastructure
"hanzo-repl", # REPL interface
"hanzoai", # SDK client library
]
# Removed packages (should not exist)
removed_packages = [
"hanzo-cli", # Merged into hanzo
"hanzo-mcp-client", # Removed - using official client
"hanzo-a2a", # Empty - removed
"hanzo-cluster", # Empty - removed
"hanzo-miner", # Empty - removed
"hanzo-tools", # Empty - removed
]
print("\n1. PACKAGE STRUCTURE CHECK")
print("-" * 40)
# Check expected packages exist
print("\n✅ Active Packages (should exist):")
for pkg in expected_packages:
pkg_dir = pkg_path / pkg
if pkg_dir.exists():
# Check for pyproject.toml
pyproject = pkg_dir / "pyproject.toml"
has_pyproject = "✓" if pyproject.exists() else "✗"
print(f" ✓ {pkg:20} [pyproject.toml: {has_pyproject}]")
else:
print(f" ✗ {pkg:20} [MISSING]")
print("\n🗑️ Removed Packages (should NOT exist):")
for pkg in removed_packages:
pkg_dir = pkg_path / pkg
if not pkg_dir.exists():
print(f" ✓ {pkg:20} [Successfully removed]")
else:
print(f" ✗ {pkg:20} [STILL EXISTS - needs removal]")
print("\n2. TEST EXECUTION")
print("-" * 40)
# Run tests for each package with tests
test_results = {}
packages_with_tests = ["hanzo-mcp", "hanzo-aci", "hanzo-network", "hanzo-agents", "hanzo-memory"]
for pkg in packages_with_tests:
pkg_dir = pkg_path / pkg
if pkg_dir.exists():
print(f"\nTesting {pkg}...")
success, stdout, stderr = run_command(
"python -m pytest tests/ -v --tb=short -x 2>&1 | head -20",
cwd=str(pkg_dir)
)
if "passed" in stdout or "PASSED" in stdout:
test_results[pkg] = "PASSED"
print(f" ✓ Tests found and running")
elif "no tests ran" in stdout.lower() or "not found" in stderr.lower():
test_results[pkg] = "NO TESTS"
print(f" ⚠ No tests found")
else:
test_results[pkg] = "FAILED"
print(f" ✗ Tests failed or error")
print("\n3. PACKAGE DEPENDENCIES")
print("-" * 40)
# Check main hanzo package dependencies
hanzo_pyproject = pkg_path / "hanzo" / "pyproject.toml"
if hanzo_pyproject.exists():
with open(hanzo_pyproject) as f:
content = f.read()
if "hanzo-cli" not in content and "hanzo-mcp-client" not in content:
print("✓ Main hanzo package cleaned of removed dependencies")
else:
print("✗ Main hanzo package still has references to removed packages")
print("\n4. SUMMARY")
print("-" * 40)
total_packages = len([p for p in expected_packages if (pkg_path / p).exists()])
print(f"Total active packages: {total_packages}/{len(expected_packages)}")
removed_count = len([p for p in removed_packages if not (pkg_path / p).exists()])
print(f"Successfully removed: {removed_count}/{len(removed_packages)}")
if test_results:
passed = len([v for v in test_results.values() if v == "PASSED"])
print(f"Packages with passing tests: {passed}/{len(test_results)}")
print("\n" + "=" * 60)
print("CLEANUP VERIFICATION COMPLETE")
print("=" * 60)
# Return success if all expected packages exist and all removed packages are gone
all_expected_exist = all((pkg_path / p).exists() for p in expected_packages)
all_removed_gone = all(not (pkg_path / p).exists() for p in removed_packages)
if all_expected_exist and all_removed_gone:
print("\n✅ Package cleanup successful!")
return 0
else:
print("\n⚠️ Some issues remain - review output above")
return 1
if __name__ == "__main__":
sys.exit(test_package_structure())
-108
View File
@@ -1,108 +0,0 @@
#!/usr/bin/env python
"""Test script to verify hanzo package installation and functionality."""
import sys
import subprocess
import traceback
def test_import():
"""Test basic imports from hanzo package."""
print("Testing imports...")
try:
import hanzo
print(f"✓ hanzo imported successfully (version: {hanzo.__version__})")
# Test router import
try:
from hanzo import router
print("✓ hanzo.router imported successfully")
except ImportError as e:
print(f"✗ Failed to import hanzo.router: {e}")
# Test core exports
exports = ["Router", "completion", "acompletion", "embedding", "aembedding",
"Agent", "Network", "Tool", "MCPServer", "Client", "AsyncClient"]
for export in exports:
if hasattr(hanzo, export):
print(f"✓ hanzo.{export} available")
else:
print(f"✗ hanzo.{export} not available")
except ImportError as e:
print(f"✗ Failed to import hanzo: {e}")
traceback.print_exc()
return False
return True
def test_cli_commands():
"""Test CLI commands."""
print("\nTesting CLI commands...")
commands = [
("hanzo", "--version"),
("hanzo", "--help"),
("hanzo-mcp", "--help"),
]
for cmd in commands:
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=5)
if result.returncode == 0:
print(f"✓ {' '.join(cmd)} works")
else:
print(f"✗ {' '.join(cmd)} failed: {result.stderr}")
except subprocess.TimeoutExpired:
print(f"✗ {' '.join(cmd)} timed out")
except FileNotFoundError:
print(f"✗ {' '.join(cmd)} command not found")
except Exception as e:
print(f"✗ {' '.join(cmd)} error: {e}")
def test_router_functionality():
"""Test basic router functionality."""
print("\nTesting router functionality...")
try:
from hanzo import router
# Check if main functions exist
if hasattr(router, 'completion'):
print("✓ router.completion function available")
else:
print("✗ router.completion function not available")
if hasattr(router, 'Router'):
print("✓ router.Router class available")
else:
print("✗ router.Router class not available")
except ImportError as e:
print(f"✗ Could not test router functionality: {e}")
def main():
"""Run all tests."""
print("=" * 60)
print("Hanzo Package Installation Test")
print("=" * 60)
# Check Python version
print(f"Python version: {sys.version}")
print()
# Run tests
test_import()
test_cli_commands()
test_router_functionality()
print("\n" + "=" * 60)
print("Test complete!")
print("=" * 60)
if __name__ == "__main__":
main()
-121
View File
@@ -1,121 +0,0 @@
#!/usr/bin/env python3
"""Test script to verify all packages in the monorepo are healthy."""
import subprocess
import sys
from pathlib import Path
from typing import Dict, List, Tuple
# Disable DataDog tracing
import os
os.environ["DD_TRACE_ENABLED"] = "false"
os.environ["DATADOG_TRACE_ENABLED"] = "false"
# Colors for output
CYAN = "\033[0;36m"
GREEN = "\033[0;32m"
RED = "\033[0;31m"
YELLOW = "\033[0;33m"
NC = "\033[0m" # No Color
def test_package_import(package_name: str, import_name: str = None) -> Tuple[bool, str]:
"""Test if a package can be imported."""
import_name = import_name or package_name.replace("-", "_")
try:
cmd = [sys.executable, "-c", f"import {import_name}; print('{import_name} imported successfully')"]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
if result.returncode == 0:
return True, result.stdout.strip()
else:
return False, result.stderr.strip()
except Exception as e:
return False, str(e)
def test_package_version(package_name: str) -> Tuple[bool, str]:
"""Test if we can get the package version."""
try:
cmd = [sys.executable, "-m", "pip", "show", package_name]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
if result.returncode == 0:
for line in result.stdout.split("\n"):
if line.startswith("Version:"):
return True, line.split(":")[1].strip()
return False, "Version not found"
except Exception as e:
return False, str(e)
def main():
"""Main test function."""
print(f"{CYAN}Hanzo Python SDK Monorepo Health Check{NC}\n")
packages = [
("hanzoai", "hanzoai"),
("hanzo-agents", "hanzo_agents"),
("hanzo-mcp", "hanzo_mcp"),
("hanzo-cli", "hanzo_cli"),
("hanzo-repl", "hanzo_repl"),
("hanzo-memory", "hanzo_memory"),
("hanzo-network", "hanzo_network"),
("hanzo-mcp-client", "hanzo_mcp_client"),
("hanzo-aci", "dev_aci"), # Note: This publishes as dev-aci
]
all_passed = True
results = []
for package_name, import_name in packages:
print(f"\n{GREEN}Testing {package_name}...{NC}")
# Test import
import_success, import_msg = test_package_import(package_name, import_name)
if import_success:
print(f" ✓ Import: {import_msg}")
else:
print(f" {RED}✗ Import failed: {import_msg}{NC}")
all_passed = False
# Test version
version_success, version = test_package_version(package_name)
if version_success:
print(f" ✓ Version: {version}")
else:
print(f" {YELLOW}⚠ Version check failed: {version}{NC}")
results.append({
"package": package_name,
"import_success": import_success,
"version": version if version_success else None
})
# Summary
print(f"\n{CYAN}Summary:{NC}")
successful = sum(1 for r in results if r["import_success"])
print(f" Packages tested: {len(results)}")
print(f" Successful imports: {successful}")
print(f" Failed imports: {len(results) - successful}")
if all_passed:
print(f"\n{GREEN}✅ All packages are healthy!{NC}")
else:
print(f"\n{RED}❌ Some packages have issues.{NC}")
print(f"\nFailed packages:")
for r in results:
if not r["import_success"]:
print(f" - {r['package']}")
# Test PostHog availability
print(f"\n{CYAN}Analytics Check:{NC}")
try:
from hanzo_mcp.analytics import Analytics
print(f" {GREEN}✓ PostHog analytics available in hanzo-mcp{NC}")
except ImportError:
print(f" {YELLOW}⚠ PostHog analytics not available{NC}")
return 0 if all_passed else 1
if __name__ == "__main__":
sys.exit(main())
-55
View File
@@ -1,55 +0,0 @@
#!/usr/bin/env python
"""Test hanzo router integration."""
import sys
import os
# Add the site-packages to path if needed
site_packages = "/opt/homebrew/lib/python3.12/site-packages"
if site_packages not in sys.path:
sys.path.insert(0, site_packages)
print("Testing hanzo router integration...")
print(f"Python path: {sys.path[:3]}...")
try:
# Try importing hanzo
import hanzo
print(f"✓ Imported hanzo version {hanzo.__version__}")
# Check router
if hasattr(hanzo, 'router'):
print("✓ hanzo.router is available")
# Test router functions
if hasattr(hanzo.router, 'completion'):
print("✓ hanzo.router.completion is available")
else:
print("✗ hanzo.router.completion is not available")
if hasattr(hanzo.router, 'Router'):
print("✓ hanzo.router.Router is available")
else:
print("✗ hanzo.router.Router is not available")
else:
print("✗ hanzo.router is not available")
# Try direct import
try:
from hanzo import router
print("✓ Direct import 'from hanzo import router' works")
except ImportError as e:
print(f"✗ Direct import failed: {e}")
except ImportError as e:
print(f"✗ Failed to import hanzo: {e}")
# Try to debug the issue
hanzo_path = os.path.join(site_packages, "hanzo")
if os.path.exists(hanzo_path):
print(f"Hanzo directory exists at: {hanzo_path}")
print(f"Contents: {os.listdir(hanzo_path)}")
else:
print(f"Hanzo directory does not exist at: {hanzo_path}")
print("\nTest complete!")