diff --git a/.github/BRANCH_PROTECTION.md b/.github/BRANCH_PROTECTION.md index c1a9b48e..6873f6e0 100644 --- a/.github/BRANCH_PROTECTION.md +++ b/.github/BRANCH_PROTECTION.md @@ -65,16 +65,16 @@ cd control-plane go build ./... # Test cross-compilation -GOOS=linux GOARCH=amd64 go build ./cmd/brain-server -GOOS=darwin GOARCH=amd64 go build ./cmd/brain-server -GOOS=windows GOARCH=amd64 go build ./cmd/brain-server +GOOS=linux GOARCH=amd64 go build ./cmd/haxen-server +GOOS=darwin GOARCH=amd64 go build ./cmd/haxen-server +GOOS=windows GOARCH=amd64 go build ./cmd/haxen-server ``` ### Docker Build Failures ```bash # Test Docker build locally -docker build -f deployments/docker/Dockerfile.control-plane -t brain-control-plane:test . -docker run --rm brain-control-plane:test --help +docker build -f deployments/docker/Dockerfile.control-plane -t haxen-control-plane:test . +docker run --rm haxen-control-plane:test --help ``` ## Emergency Merges diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index 55f48717..e0dd7eb3 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -1,6 +1,6 @@ --- name: Feature Request -about: Suggest an idea for Brain +about: Suggest an idea for Haxen labels: enhancement --- diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md index dd7d1105..ab0253a9 100644 --- a/.github/ISSUE_TEMPLATE/question.md +++ b/.github/ISSUE_TEMPLATE/question.md @@ -1,6 +1,6 @@ --- name: Question -about: Ask a question about using Brain +about: Ask a question about using Haxen labels: question --- diff --git a/.github/workflows/control-plane.yml b/.github/workflows/control-plane.yml index 2a866c73..acaea0cf 100644 --- a/.github/workflows/control-plane.yml +++ b/.github/workflows/control-plane.yml @@ -113,7 +113,7 @@ jobs: working-directory: control-plane run: | echo "Building for ${GOOS}/${GOARCH}" - go build -o /tmp/brain-server-${GOOS}-${GOARCH} ./cmd/brain-server + go build -o /tmp/haxen-server-${GOOS}-${GOARCH} ./cmd/haxen-server # Summary job that depends on all critical checks required-checks: diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 9d78a5d9..30fcd270 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -30,10 +30,10 @@ jobs: context: . file: deployments/docker/Dockerfile.control-plane load: true - tags: brain-control-plane:test + tags: haxen-control-plane:test - name: Smoke test control plane image - run: docker run --rm brain-control-plane:test --help + run: docker run --rm haxen-control-plane:test --help # Summary job that depends on all critical checks required-checks: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9c683518..b54071f7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -150,7 +150,7 @@ jobs: OWNER: ${{ github.repository_owner }} run: | owner="$(echo "${OWNER}" | tr '[:upper:]' '[:lower:]')" - image="ghcr.io/${owner}/brain-control-plane" + image="ghcr.io/${owner}/haxen-control-plane" if [ "${EVENT_NAME}" = "push" ]; then tag="${REF_NAME}" else diff --git a/.goreleaser.yml b/.goreleaser.yml index a8ce163c..e22f7bc9 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -1,4 +1,4 @@ -project_name: brain-control-plane +project_name: haxen-control-plane before: hooks: @@ -6,10 +6,10 @@ before: - npm --prefix control-plane/web/client run build builds: - - id: brain-control-plane + - id: haxen-control-plane dir: control-plane main: ./cmd/server - binary: brain-server + binary: haxen-server env: - CGO_ENABLED=0 goos: @@ -26,9 +26,9 @@ builds: - -s -w archives: - - id: brain-control-plane + - id: haxen-control-plane builds: - - brain-control-plane + - haxen-control-plane name_template: "{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}" format_overrides: - goos: windows diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 88c788e3..bd711610 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -2,7 +2,7 @@ ## Our Pledge -We as members, contributors, and leaders pledge to make participation in the Brain project a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. +We as members, contributors, and leaders pledge to make participation in the Haxen project a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. diff --git a/README.md b/README.md index 16d0ca46..8e05b257 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ -# Brain Monorepo +# Haxen Monorepo -Brain is an open-source platform for building, deploying, and operating production-grade AI agents. This repository brings together the control plane, language-specific SDKs, deployment assets, and documentation required to run Brain in your own environment. +Haxen is an open-source platform for building, deploying, and operating production-grade AI agents. This repository brings together the control plane, language-specific SDKs, deployment assets, and documentation required to run Haxen in your own environment. ## Repository Layout @@ -17,8 +17,8 @@ Brain is an open-source platform for building, deploying, and operating producti ## Quick Start ```bash -git clone https://github.com/your-org/brain.git -cd brain +git clone https://github.com/your-org/haxen.git +cd haxen ./scripts/install.sh # install Go, Python, and JS dependencies ./scripts/build-all.sh # build control plane and SDKs ./scripts/test-all.sh # run repository-wide test suites @@ -57,5 +57,5 @@ We welcome issues and pull requests! Please review: ## License -Brain is licensed under the Apache 2.0 License. See `LICENSE` for details. +Haxen is licensed under the Apache 2.0 License. See `LICENSE` for details. diff --git a/control-plane/.env.dev b/control-plane/.env.dev index cad4ad05..3e639e02 100644 --- a/control-plane/.env.dev +++ b/control-plane/.env.dev @@ -1,7 +1,7 @@ -BRAIN_STORAGE_MODE="postgresql" -BRAIN_STORAGE_POSTGRES_URL="postgres://postgres@localhost:5432/testdb?sslmode=disable" -BRAIN_STORAGE_POSTGRES_MAX_CONNECTIONS="10" -BRAIN_STORAGE_POSTGRES_MAX_IDLE_CONNECTIONS="2" -BRAIN_STORAGE_POSTGRES_CONNECTION_TIMEOUT="30s" -BRAIN_STORAGE_POSTGRES_QUERY_TIMEOUT="30s" -BRAIN_STORAGE_POSTGRES_ENABLE_AUTO_MIGRATION="true" +HAXEN_STORAGE_MODE="postgresql" +HAXEN_STORAGE_POSTGRES_URL="postgres://postgres@localhost:5432/testdb?sslmode=disable" +HAXEN_STORAGE_POSTGRES_MAX_CONNECTIONS="10" +HAXEN_STORAGE_POSTGRES_MAX_IDLE_CONNECTIONS="2" +HAXEN_STORAGE_POSTGRES_CONNECTION_TIMEOUT="30s" +HAXEN_STORAGE_POSTGRES_QUERY_TIMEOUT="30s" +HAXEN_STORAGE_POSTGRES_ENABLE_AUTO_MIGRATION="true" diff --git a/control-plane/.env.example b/control-plane/.env.example index 125ff5a1..322c11a3 100644 --- a/control-plane/.env.example +++ b/control-plane/.env.example @@ -1,53 +1,53 @@ -# Brain Server Environment Variables +# Haxen Server Environment Variables # Copy this file to .env and modify values as needed -# Core Brain Configuration -BRAIN_PORT=8080 -BRAIN_MODE=local -BRAIN_CONFIG_FILE=./config/brain.yaml +# Core Haxen Configuration +HAXEN_PORT=8080 +HAXEN_MODE=local +HAXEN_CONFIG_FILE=./config/haxen.yaml # Database Configuration (for local mode) -BRAIN_STORAGE_LOCAL_DATABASE_PATH=./brain_local.db -BRAIN_STORAGE_LOCAL_KV_STORE_PATH=./brain_local.bolt +HAXEN_STORAGE_LOCAL_DATABASE_PATH=./haxen_local.db +HAXEN_STORAGE_LOCAL_KV_STORE_PATH=./haxen_local.bolt # UI Configuration -BRAIN_UI_ENABLED=true -BRAIN_UI_MODE=embedded -BRAIN_UI_SOURCE_PATH=./web/client -BRAIN_UI_DIST_PATH=./web/client/dist -BRAIN_UI_DEV_PORT=5173 +HAXEN_UI_ENABLED=true +HAXEN_UI_MODE=embedded +HAXEN_UI_SOURCE_PATH=./web/client +HAXEN_UI_DIST_PATH=./web/client/dist +HAXEN_UI_DEV_PORT=5173 # API Configuration -BRAIN_API_CORS_ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173,http://localhost:8080 -BRAIN_API_CORS_ALLOWED_METHODS=GET,POST,PUT,DELETE,OPTIONS -BRAIN_API_CORS_ALLOWED_HEADERS=Origin,Content-Type,Accept,Authorization,X-Requested-With -BRAIN_API_CORS_EXPOSED_HEADERS=Content-Length,X-Total-Count -BRAIN_API_CORS_ALLOW_CREDENTIALS=true +HAXEN_API_CORS_ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173,http://localhost:8080 +HAXEN_API_CORS_ALLOWED_METHODS=GET,POST,PUT,DELETE,OPTIONS +HAXEN_API_CORS_ALLOWED_HEADERS=Origin,Content-Type,Accept,Authorization,X-Requested-With +HAXEN_API_CORS_EXPOSED_HEADERS=Content-Length,X-Total-Count +HAXEN_API_CORS_ALLOW_CREDENTIALS=true # Cloud Configuration (if using cloud mode) -# BRAIN_CLOUD_ENABLED=false -# BRAIN_CLOUD_API_KEY=your-api-key-here +# HAXEN_CLOUD_ENABLED=false +# HAXEN_CLOUD_API_KEY=your-api-key-here # Storage Configuration -BRAIN_STORAGE_MODE=local - -# PostgreSQL Storage Configuration (when BRAIN_STORAGE_MODE=postgresql) -# BRAIN_STORAGE_POSTGRES_URL=postgresql://user:password@localhost:5432/brain?sslmode=disable -# BRAIN_STORAGE_POSTGRES_MAX_CONNECTIONS=25 -# BRAIN_STORAGE_POSTGRES_MAX_IDLE_CONNECTIONS=5 -# BRAIN_STORAGE_POSTGRES_CONNECTION_TIMEOUT=30s -# BRAIN_STORAGE_POSTGRES_QUERY_TIMEOUT=30s -# BRAIN_STORAGE_POSTGRES_ENABLE_MEMORY_FALLBACK=true -# BRAIN_STORAGE_POSTGRES_ENABLE_DID_FALLBACK=true -# BRAIN_STORAGE_POSTGRES_ENABLE_VC_FALLBACK=true -# BRAIN_STORAGE_POSTGRES_ENABLE_AUTO_MIGRATION=true - -# Cloud Storage Configuration (when BRAIN_STORAGE_MODE=cloud) -# BRAIN_STORAGE_CLOUD_POSTGRES_URL=postgresql://user:password@localhost:5432/brain -# BRAIN_STORAGE_CLOUD_REDIS_URL=redis://localhost:6379 -# BRAIN_STORAGE_CLOUD_MAX_CONNECTIONS=50 -# BRAIN_STORAGE_CLOUD_CONNECTION_POOL=true -# BRAIN_STORAGE_CLOUD_REPLICATION_MODE=async +HAXEN_STORAGE_MODE=local + +# PostgreSQL Storage Configuration (when HAXEN_STORAGE_MODE=postgresql) +# HAXEN_STORAGE_POSTGRES_URL=postgresql://user:password@localhost:5432/haxen?sslmode=disable +# HAXEN_STORAGE_POSTGRES_MAX_CONNECTIONS=25 +# HAXEN_STORAGE_POSTGRES_MAX_IDLE_CONNECTIONS=5 +# HAXEN_STORAGE_POSTGRES_CONNECTION_TIMEOUT=30s +# HAXEN_STORAGE_POSTGRES_QUERY_TIMEOUT=30s +# HAXEN_STORAGE_POSTGRES_ENABLE_MEMORY_FALLBACK=true +# HAXEN_STORAGE_POSTGRES_ENABLE_DID_FALLBACK=true +# HAXEN_STORAGE_POSTGRES_ENABLE_VC_FALLBACK=true +# HAXEN_STORAGE_POSTGRES_ENABLE_AUTO_MIGRATION=true + +# Cloud Storage Configuration (when HAXEN_STORAGE_MODE=cloud) +# HAXEN_STORAGE_CLOUD_POSTGRES_URL=postgresql://user:password@localhost:5432/haxen +# HAXEN_STORAGE_CLOUD_REDIS_URL=redis://localhost:6379 +# HAXEN_STORAGE_CLOUD_MAX_CONNECTIONS=50 +# HAXEN_STORAGE_CLOUD_CONNECTION_POOL=true +# HAXEN_STORAGE_CLOUD_REPLICATION_MODE=async # Development/Debug # GIN_MODE=debug diff --git a/control-plane/README.md b/control-plane/README.md index 8378f21f..de67e00e 100644 --- a/control-plane/README.md +++ b/control-plane/README.md @@ -1,6 +1,6 @@ -# Brain Control Plane +# Haxen Control Plane -The Brain control plane orchestrates agent workflows, manages verifiable credentials, serves the admin UI, and exposes REST/gRPC APIs consumed by the SDKs. +The Haxen control plane orchestrates agent workflows, manages verifiable credentials, serves the admin UI, and exposes REST/gRPC APIs consumed by the SDKs. ## Requirements @@ -16,12 +16,12 @@ The Brain control plane orchestrates agent workflows, manages verifiable credent go mod download npm --prefix web/client install -# Run database migrations (requires BRAIN_DATABASE_URL) -goose -dir ./migrations postgres "$BRAIN_DATABASE_URL" up +# Run database migrations (requires HAXEN_DATABASE_URL) +goose -dir ./migrations postgres "$HAXEN_DATABASE_URL" up # Start the control plane -BRAIN_DATABASE_URL=postgres://brain:brain@localhost:5432/brain?sslmode=disable \ -BRAIN_REDIS_URL=redis://localhost:6379/0 \ +HAXEN_DATABASE_URL=postgres://haxen:haxen@localhost:5432/haxen?sslmode=disable \ +HAXEN_REDIS_URL=redis://localhost:6379/0 \ go run ./cmd/server ``` @@ -29,12 +29,12 @@ Visit `http://localhost:8080/ui/` to access the embedded admin UI. ## Configuration -Environment variables override `config/brain.yaml`. Common options: +Environment variables override `config/haxen.yaml`. Common options: -- `BRAIN_DATABASE_URL` – PostgreSQL DSN -- `BRAIN_REDIS_URL` – Redis connection string -- `BRAIN_HTTP_ADDR` – HTTP listen address (`0.0.0.0:8080` by default) -- `BRAIN_LOG_LEVEL` – log verbosity (`info`, `debug`, etc.) +- `HAXEN_DATABASE_URL` – PostgreSQL DSN +- `HAXEN_REDIS_URL` – Redis connection string +- `HAXEN_HTTP_ADDR` – HTTP listen address (`0.0.0.0:8080` by default) +- `HAXEN_LOG_LEVEL` – log verbosity (`info`, `debug`, etc.) Sample config files live in `config/`. @@ -53,8 +53,8 @@ Run the Go server alongside the UI so API calls resolve locally. During producti Migrations use [Goose](https://github.com/pressly/goose): ```bash -BRAIN_DATABASE_URL=postgres://brain:brain@localhost:5432/brain?sslmode=disable \ -goose -dir ./migrations postgres "$BRAIN_DATABASE_URL" status +HAXEN_DATABASE_URL=postgres://haxen:haxen@localhost:5432/haxen?sslmode=disable \ +goose -dir ./migrations postgres "$HAXEN_DATABASE_URL" status ``` ## Testing diff --git a/control-plane/build-single-binary.sh b/control-plane/build-single-binary.sh index c5837066..32deb2f2 100755 --- a/control-plane/build-single-binary.sh +++ b/control-plane/build-single-binary.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Brain Single Binary Builder +# Haxen Single Binary Builder # This script creates a single, portable binary that includes: # - Go backend with universal path management # - Embedded UI @@ -142,21 +142,21 @@ package main import ( "fmt" "strings" - "github.com/your-org/brain/control-plane/internal/utils" + "github.com/your-org/haxen/control-plane/internal/utils" ) func main() { - dirs, err := utils.GetBrainDataDirectories() + dirs, err := utils.GetHaxenDataDirectories() if err != nil { fmt.Printf("ERROR: %v\n", err) return } - fmt.Printf("Brain Home: %s\n", dirs.BrainHome) + fmt.Printf("Haxen Home: %s\n", dirs.HaxenHome) - // Verify that Brain Home points to ~/.brain - if !strings.HasSuffix(dirs.BrainHome, ".brain") { - fmt.Printf("ERROR: Brain Home should end with .brain, got: %s\n", dirs.BrainHome) + // Verify that Haxen Home points to ~/.haxen + if !strings.HasSuffix(dirs.HaxenHome, ".haxen") { + fmt.Printf("ERROR: Haxen Home should end with .haxen, got: %s\n", dirs.HaxenHome) return } @@ -168,9 +168,9 @@ func main() { } fmt.Printf("Database Path: %s\n", dbPath) - // Verify database path is in ~/.brain/data/ - if !strings.Contains(dbPath, ".brain/data/brain.db") { - fmt.Printf("ERROR: Database path should be in ~/.brain/data/, got: %s\n", dbPath) + // Verify database path is in ~/.haxen/data/ + if !strings.Contains(dbPath, ".haxen/data/haxen.db") { + fmt.Printf("ERROR: Database path should be in ~/.haxen/data/, got: %s\n", dbPath) return } @@ -181,7 +181,7 @@ func main() { return } - fmt.Println("SUCCESS: Path management system working correctly - database will be stored in ~/.brain/") + fmt.Println("SUCCESS: Path management system working correctly - database will be stored in ~/.haxen/") } EOF @@ -266,7 +266,7 @@ build_binary() { -ldflags "$LDFLAGS" \ -tags "embedded sqlite_fts5" \ -o "$OUTPUT_DIR/$output_name" \ - ./cmd/brain-server + ./cmd/haxen-server if [ $? -eq 0 ]; then # Get file size @@ -305,10 +305,10 @@ build_all_binaries() { # Define platforms to build declare -a platforms=( - # "linux:amd64:brain-linux-amd64" - # "linux:arm64:brain-linux-arm64" - # "darwin:amd64:brain-darwin-amd64" - "darwin:arm64:brain-darwin-arm64" + # "linux:amd64:haxen-linux-amd64" + # "linux:arm64:haxen-linux-arm64" + # "darwin:amd64:haxen-darwin-amd64" + "darwin:arm64:haxen-darwin-arm64" ) for platform in "${platforms[@]}"; do @@ -336,10 +336,10 @@ generate_metadata() { # Generate SHA256 checksums if command_exists sha256sum; then - sha256sum brain-* > checksums.txt 2>/dev/null || true + sha256sum haxen-* > checksums.txt 2>/dev/null || true print_success "Generated checksums.txt" elif command_exists shasum; then - shasum -a 256 brain-* > checksums.txt 2>/dev/null || true + shasum -a 256 haxen-* > checksums.txt 2>/dev/null || true print_success "Generated checksums.txt" else print_warning "No checksum utility found, skipping checksum generation" @@ -347,7 +347,7 @@ generate_metadata() { # Generate build info cat > build-info.txt << EOF -Brain Single Binary Build Information +Haxen Single Binary Build Information ==================================== Build Version: $VERSION @@ -358,31 +358,31 @@ Build OS: $(uname -s) Build Arch: $(uname -m) Features: -- Universal Path Management (stores data in ~/.brain/) +- Universal Path Management (stores data in ~/.haxen/) - Embedded Web UI - Cross-platform compatibility - Single binary deployment Usage: - ./brain- # Start Brain server with UI - ./brain- --help # Show help - ./brain- --backend-only # Start without UI + ./haxen- # Start Haxen server with UI + ./haxen- --help # Show help + ./haxen- --backend-only # Start without UI Data Storage: -All Brain data is stored in ~/.brain/ directory: -- ~/.brain/data/brain.db # Main database -- ~/.brain/data/brain.bolt # Cache/KV store -- ~/.brain/data/keys/ # DID cryptographic keys -- ~/.brain/data/did_registries/ # DID registries -- ~/.brain/data/vcs/ # Verifiable credentials -- ~/.brain/agents/ # Installed agents -- ~/.brain/logs/ # Application logs -- ~/.brain/config/ # User configurations +All Haxen data is stored in ~/.haxen/ directory: +- ~/.haxen/data/haxen.db # Main database +- ~/.haxen/data/haxen.bolt # Cache/KV store +- ~/.haxen/data/keys/ # DID cryptographic keys +- ~/.haxen/data/did_registries/ # DID registries +- ~/.haxen/data/vcs/ # Verifiable credentials +- ~/.haxen/agents/ # Installed agents +- ~/.haxen/logs/ # Application logs +- ~/.haxen/config/ # User configurations Environment Variables: -- BRAIN_HOME: Override default ~/.brain directory -- BRAIN_PORT: Override default port (8080) -- BRAIN_CONFIG_FILE: Override config file location +- HAXEN_HOME: Override default ~/.haxen directory +- HAXEN_PORT: Override default port (8080) +- HAXEN_CONFIG_FILE: Override config file location EOF @@ -397,27 +397,27 @@ create_distribution() { # Create a README for the distribution cat > "$OUTPUT_DIR/README.md" << 'EOF' -# Brain Single Binary Distribution +# Haxen Single Binary Distribution -This package contains pre-built Brain binaries for multiple platforms. +This package contains pre-built Haxen binaries for multiple platforms. ## Quick Start 1. Download the appropriate binary for your platform: - - `brain-linux-amd64` - Linux (Intel/AMD 64-bit) - - `brain-linux-arm64` - Linux (ARM 64-bit) - - `brain-darwin-amd64` - macOS (Intel) - - `brain-darwin-arm64` - macOS (Apple Silicon) - - `brain-windows-amd64.exe` - Windows (64-bit) + - `haxen-linux-amd64` - Linux (Intel/AMD 64-bit) + - `haxen-linux-arm64` - Linux (ARM 64-bit) + - `haxen-darwin-amd64` - macOS (Intel) + - `haxen-darwin-arm64` - macOS (Apple Silicon) + - `haxen-windows-amd64.exe` - Windows (64-bit) 2. Make the binary executable (Linux/macOS): ```bash - chmod +x brain-* + chmod +x haxen-* ``` -3. Run Brain: +3. Run Haxen: ```bash - ./brain-linux-amd64 + ./haxen-linux-amd64 ``` 4. Open your browser to http://localhost:8080 @@ -425,26 +425,26 @@ This package contains pre-built Brain binaries for multiple platforms. ## Features - **Single Binary**: Everything bundled in one executable -- **Universal Storage**: All data stored in `~/.brain/` directory +- **Universal Storage**: All data stored in `~/.haxen/` directory - **Embedded UI**: Web interface included in binary - **Cross-Platform**: Works on Linux, macOS, and Windows - **Portable**: Run from anywhere, data stays consistent ## Configuration -Brain can be configured via: -- Environment variables (BRAIN_HOME, BRAIN_PORT, etc.) -- Configuration file (`~/.brain/brain.yaml`) +Haxen can be configured via: +- Environment variables (HAXEN_HOME, HAXEN_PORT, etc.) +- Configuration file (`~/.haxen/haxen.yaml`) - Command line flags (`--port`, `--backend-only`, etc.) ## Data Directory -All Brain data is stored in `~/.brain/`: +All Haxen data is stored in `~/.haxen/`: ``` -~/.brain/ +~/.haxen/ ├── data/ -│ ├── brain.db # Main database -│ ├── brain.bolt # Cache +│ ├── haxen.db # Main database +│ ├── haxen.bolt # Cache │ ├── keys/ # Cryptographic keys │ ├── did_registries/ # DID registries │ └── vcs/ # Verifiable credentials @@ -455,7 +455,7 @@ All Brain data is stored in `~/.brain/`: ## Support -For issues and documentation, visit: https://github.com/your-org/brain +For issues and documentation, visit: https://github.com/your-org/haxen EOF print_success "Created distribution README.md" @@ -473,7 +473,7 @@ show_summary() { if [ -d "$OUTPUT_DIR" ]; then print_status "Output directory: $OUTPUT_DIR" print_status "Built files:" - ls -la "$OUTPUT_DIR" | grep -E "(brain-|checksums|build-info|README)" + ls -la "$OUTPUT_DIR" | grep -E "(haxen-|checksums|build-info|README)" # Calculate total size if command_exists du; then @@ -487,21 +487,21 @@ show_summary() { echo "" print_status "To test your binary:" echo " cd $OUTPUT_DIR" - echo " ./brain-$(uname -s | tr '[:upper:]' '[:lower:]')-$(uname -m | sed 's/x86_64/amd64/')" + echo " ./haxen-$(uname -s | tr '[:upper:]' '[:lower:]')-$(uname -m | sed 's/x86_64/amd64/')" echo "" print_status "The binary includes:" echo " ✅ Go backend with universal path management" echo " ✅ Embedded web UI" echo " ✅ All dependencies bundled" echo " ✅ Cross-platform compatibility" - echo " ✅ Portable deployment (stores data in ~/.brain/)" + echo " ✅ Portable deployment (stores data in ~/.haxen/)" } # Main build function main() { - print_header "Brain Single Binary Builder" + print_header "Haxen Single Binary Builder" - echo "Building Brain single binary with:" + echo "Building Haxen single binary with:" echo " • Universal path management" echo " • Embedded web UI" echo " • Cross-platform support" @@ -531,7 +531,7 @@ case "${1:-}" in test_path_system ;; "help"|"-h"|"--help") - echo "Brain Single Binary Builder" + echo "Haxen Single Binary Builder" echo "" echo "Usage:" echo " $0 Build complete single binary package" diff --git a/control-plane/cmd/brain-server/main.go b/control-plane/cmd/haxen-server/main.go similarity index 83% rename from control-plane/cmd/brain-server/main.go rename to control-plane/cmd/haxen-server/main.go index 87ec90ee..13b68b3f 100644 --- a/control-plane/cmd/brain-server/main.go +++ b/control-plane/cmd/haxen-server/main.go @@ -1,11 +1,11 @@ package main import ( - "github.com/your-org/brain/control-plane/internal/cli" - "github.com/your-org/brain/control-plane/internal/config" - "github.com/your-org/brain/control-plane/internal/server" - "github.com/your-org/brain/control-plane/internal/utils" - "github.com/your-org/brain/control-plane/web/client" + "github.com/your-org/haxen/control-plane/internal/cli" + "github.com/your-org/haxen/control-plane/internal/config" + "github.com/your-org/haxen/control-plane/internal/server" + "github.com/your-org/haxen/control-plane/internal/utils" + "github.com/your-org/haxen/control-plane/web/client" "fmt" "log" "os" @@ -21,14 +21,14 @@ import ( var ( loadConfigFunc = loadConfig - newBrainServerFunc = server.NewBrainServer + newHaxenServerFunc = server.NewHaxenServer buildUIFunc = buildUI openBrowserFunc = openBrowser sleepFunc = time.Sleep waitForShutdownFunc = func() { select {} } commandRunner = defaultCommandRunner browserLauncher = defaultBrowserLauncher - startBrainServerFunc = defaultStartBrainServer + startHaxenServerFunc = defaultStartHaxenServer ) // main function now acts as the entry point for the Cobra CLI. @@ -45,7 +45,7 @@ func main() { // runServer contains the original server startup logic. // This function will be called by the Cobra command's Run field. func runServer(cmd *cobra.Command, args []string) { - fmt.Println("Brain server starting...") + fmt.Println("Haxen server starting...") // Load configuration cfgFilePath, _ := cmd.Flags().GetString("config") @@ -57,13 +57,13 @@ func runServer(cmd *cobra.Command, args []string) { // Override port from flag if provided if cmd.Flags().Lookup("port").Changed { port, _ := cmd.Flags().GetInt("port") - cfg.Brain.Port = port + cfg.Haxen.Port = port } // Override from environment variables - if envPort := os.Getenv("BRAIN_PORT"); envPort != "" { + if envPort := os.Getenv("HAXEN_PORT"); envPort != "" { if port, err := strconv.Atoi(envPort); err == nil { - cfg.Brain.Port = port + cfg.Haxen.Port = port } } @@ -76,7 +76,7 @@ func runServer(cmd *cobra.Command, args []string) { } if !storageModeExplicit { - if envMode := os.Getenv("BRAIN_STORAGE_MODE"); envMode != "" { + if envMode := os.Getenv("HAXEN_STORAGE_MODE"); envMode != "" { cfg.Storage.Mode = envMode } } @@ -86,9 +86,9 @@ func runServer(cmd *cobra.Command, args []string) { postgresURL, _ = cmd.Flags().GetString("postgres-url") } if postgresURL == "" { - if env := os.Getenv("BRAIN_POSTGRES_URL"); env != "" { + if env := os.Getenv("HAXEN_POSTGRES_URL"); env != "" { postgresURL = env - } else if env := os.Getenv("BRAIN_STORAGE_POSTGRES_URL"); env != "" { + } else if env := os.Getenv("HAXEN_STORAGE_POSTGRES_URL"); env != "" { postgresURL = env } } @@ -101,24 +101,24 @@ func runServer(cmd *cobra.Command, args []string) { } } - if env := os.Getenv("BRAIN_STORAGE_POSTGRES_HOST"); env != "" { + if env := os.Getenv("HAXEN_STORAGE_POSTGRES_HOST"); env != "" { cfg.Storage.Postgres.Host = env } - if env := os.Getenv("BRAIN_STORAGE_POSTGRES_PORT"); env != "" { + if env := os.Getenv("HAXEN_STORAGE_POSTGRES_PORT"); env != "" { if port, err := strconv.Atoi(env); err == nil { cfg.Storage.Postgres.Port = port } } - if env := os.Getenv("BRAIN_STORAGE_POSTGRES_DATABASE"); env != "" { + if env := os.Getenv("HAXEN_STORAGE_POSTGRES_DATABASE"); env != "" { cfg.Storage.Postgres.Database = env } - if env := os.Getenv("BRAIN_STORAGE_POSTGRES_USER"); env != "" { + if env := os.Getenv("HAXEN_STORAGE_POSTGRES_USER"); env != "" { cfg.Storage.Postgres.User = env } - if env := os.Getenv("BRAIN_STORAGE_POSTGRES_PASSWORD"); env != "" { + if env := os.Getenv("HAXEN_STORAGE_POSTGRES_PASSWORD"); env != "" { cfg.Storage.Postgres.Password = env } - if env := os.Getenv("BRAIN_STORAGE_POSTGRES_SSLMODE"); env != "" { + if env := os.Getenv("HAXEN_STORAGE_POSTGRES_SSLMODE"); env != "" { cfg.Storage.Postgres.SSLMode = env } @@ -156,17 +156,17 @@ func runServer(cmd *cobra.Command, args []string) { fmt.Println("UI is already embedded in binary, skipping build.") } - // Create Brain server instance - brainServer, err := newBrainServerFunc(cfg) + // Create Haxen server instance + haxenServer, err := newHaxenServerFunc(cfg) if err != nil { - log.Fatalf("Failed to create Brain server: %v", err) + log.Fatalf("Failed to create Haxen server: %v", err) } // Start the server in a goroutine so we can open the browser go func() { - fmt.Printf("Brain server attempting to start on port %d...\n", cfg.Brain.Port) - if err := startBrainServerFunc(brainServer); err != nil { - log.Fatalf("Failed to start Brain server: %v", err) + fmt.Printf("Haxen server attempting to start on port %d...\n", cfg.Haxen.Port) + if err := startHaxenServerFunc(haxenServer); err != nil { + log.Fatalf("Failed to start Haxen server: %v", err) } }() @@ -175,7 +175,7 @@ func runServer(cmd *cobra.Command, args []string) { openBrowserFlag, _ := cmd.Flags().GetBool("open") if cfg.UI.Enabled && openBrowserFlag && !backendOnly { - uiTargetURL := fmt.Sprintf("http://localhost:%d", cfg.Brain.Port) + uiTargetURL := fmt.Sprintf("http://localhost:%d", cfg.Haxen.Port) if cfg.UI.Mode == "dev" { // Use configured dev port or environment variable devPort := cfg.UI.DevPort @@ -193,7 +193,7 @@ func runServer(cmd *cobra.Command, args []string) { openBrowserFunc(uiTargetURL) } - fmt.Printf("Brain server running. Press Ctrl+C to exit.\n") + fmt.Printf("Haxen server running. Press Ctrl+C to exit.\n") // Keep main goroutine alive waitForShutdownFunc() @@ -203,7 +203,7 @@ func runServer(cmd *cobra.Command, args []string) { // loadConfig loads configuration from file and environment variables. func loadConfig(configFile string) (*config.Config, error) { // Set environment variable prefixes - viper.SetEnvPrefix("BRAIN") + viper.SetEnvPrefix("HAXEN") viper.AutomaticEnv() // read in environment variables that match // Skip config file reading if explicitly set to /dev/null or empty @@ -214,10 +214,10 @@ func loadConfig(configFile string) (*config.Config, error) { } } else if configFile == "" { // Check for config file path from environment - if envConfigFile := os.Getenv("BRAIN_CONFIG_FILE"); envConfigFile != "" { + if envConfigFile := os.Getenv("HAXEN_CONFIG_FILE"); envConfigFile != "" { viper.SetConfigFile(envConfigFile) } else { - viper.SetConfigName("brain") // name of config file (without extension) + viper.SetConfigName("haxen") // name of config file (without extension) viper.SetConfigType("yaml") // type of the config file viper.AddConfigPath("./config") // path to look for the config file in viper.AddConfigPath(".") // optionally look for config in the working directory @@ -240,8 +240,8 @@ func loadConfig(configFile string) (*config.Config, error) { } // Apply defaults if not set - if cfg.Brain.Port == 0 { - cfg.Brain.Port = 8080 // Default port + if cfg.Haxen.Port == 0 { + cfg.Haxen.Port = 8080 // Default port } if cfg.Storage.Mode == "" { cfg.Storage.Mode = "local" // Default storage mode @@ -316,24 +316,24 @@ func loadConfig(configFile string) (*config.Config, error) { // Get the executable path and find UI relative to it execPath, err := os.Executable() if err != nil { - cfg.UI.SourcePath = filepath.Join("apps", "platform", "brain", "web", "client") + cfg.UI.SourcePath = filepath.Join("apps", "platform", "haxen", "web", "client") if _, statErr := os.Stat(cfg.UI.SourcePath); os.IsNotExist(statErr) { cfg.UI.SourcePath = filepath.Join("web", "client") } } else { execDir := filepath.Dir(execPath) // Look for web/client relative to the executable directory - // This assumes the binary is built in the brain/ directory + // This assumes the binary is built in the haxen/ directory cfg.UI.SourcePath = filepath.Join(execDir, "web", "client") - // If that doesn't exist, try going up one level (if binary is in brain/) + // If that doesn't exist, try going up one level (if binary is in haxen/) if _, err := os.Stat(cfg.UI.SourcePath); os.IsNotExist(err) { - cfg.UI.SourcePath = filepath.Join(filepath.Dir(execDir), "apps", "platform", "brain", "web", "client") + cfg.UI.SourcePath = filepath.Join(filepath.Dir(execDir), "apps", "platform", "haxen", "web", "client") } // Final fallback to current working directory if _, err := os.Stat(cfg.UI.SourcePath); os.IsNotExist(err) { - altPath := filepath.Join("apps", "platform", "brain", "web", "client") + altPath := filepath.Join("apps", "platform", "haxen", "web", "client") if _, altErr := os.Stat(altPath); altErr == nil { cfg.UI.SourcePath = altPath } else { @@ -362,14 +362,14 @@ func loadConfig(configFile string) (*config.Config, error) { } cfg.Storage.Local.KVStorePath = kvPath } - // Ensure all Brain data directories exist + // Ensure all Haxen data directories exist if _, err := utils.EnsureDataDirectories(); err != nil { - return nil, fmt.Errorf("failed to create Brain data directories: %w", err) + return nil, fmt.Errorf("failed to create Haxen data directories: %w", err) } } - fmt.Printf("Loaded config - Storage mode: %s, Brain Port: %d, UI Mode: %s, UI Enabled: %t, DID Enabled: %t\n", - cfg.Storage.Mode, cfg.Brain.Port, cfg.UI.Mode, cfg.UI.Enabled, cfg.Features.DID.Enabled) + fmt.Printf("Loaded config - Storage mode: %s, Haxen Port: %d, UI Mode: %s, UI Enabled: %t, DID Enabled: %t\n", + cfg.Storage.Mode, cfg.Haxen.Port, cfg.UI.Mode, cfg.UI.Enabled, cfg.Features.DID.Enabled) return &cfg, nil } @@ -397,7 +397,7 @@ func buildUI(cfg *config.Config) error { } // Set API proxy target for development builds - buildEnv = append(buildEnv, fmt.Sprintf("VITE_API_PROXY_TARGET=http://localhost:%d", cfg.Brain.Port)) + buildEnv = append(buildEnv, fmt.Sprintf("VITE_API_PROXY_TARGET=http://localhost:%d", cfg.Haxen.Port)) // Install dependencies if err := commandRunner(uiDir, buildEnv, "npm", "install", "--force"); err != nil { @@ -426,7 +426,7 @@ func defaultBrowserLauncher(name string, args ...string) error { return exec.Command(name, args...).Start() } -func defaultStartBrainServer(s *server.BrainServer) error { +func defaultStartHaxenServer(s *server.HaxenServer) error { return s.Start() } diff --git a/control-plane/cmd/brain-server/main_test.go b/control-plane/cmd/haxen-server/main_test.go similarity index 84% rename from control-plane/cmd/brain-server/main_test.go rename to control-plane/cmd/haxen-server/main_test.go index 710424e8..3f1133f2 100644 --- a/control-plane/cmd/brain-server/main_test.go +++ b/control-plane/cmd/haxen-server/main_test.go @@ -10,16 +10,16 @@ import ( "testing" "time" - "github.com/your-org/brain/control-plane/internal/config" - "github.com/your-org/brain/control-plane/internal/server" + "github.com/your-org/haxen/control-plane/internal/config" + "github.com/your-org/haxen/control-plane/internal/server" "github.com/spf13/cobra" "github.com/spf13/viper" ) func TestLoadConfig_DefaultsApplied(t *testing.T) { - t.Setenv("BRAIN_PORT", "") - t.Setenv("BRAIN_CONFIG_FILE", "") + t.Setenv("HAXEN_PORT", "") + t.Setenv("HAXEN_CONFIG_FILE", "") viper.Reset() cfg, err := loadConfig("/dev/null") @@ -27,8 +27,8 @@ func TestLoadConfig_DefaultsApplied(t *testing.T) { t.Fatalf("loadConfig returned error: %v", err) } - if cfg.Brain.Port != 8080 { - t.Errorf("expected default brain port 8080, got %d", cfg.Brain.Port) + if cfg.Haxen.Port != 8080 { + t.Errorf("expected default haxen port 8080, got %d", cfg.Haxen.Port) } if cfg.Storage.Mode != "local" { t.Errorf("expected default storage mode local, got %s", cfg.Storage.Mode) @@ -51,8 +51,8 @@ func TestLoadConfig_ConfigFileValues(t *testing.T) { viper.Reset() dir := t.TempDir() - file := filepath.Join(dir, "brain.yaml") - content := []byte(`brain: + file := filepath.Join(dir, "haxen.yaml") + content := []byte(`haxen: port: 9231 storage: mode: local @@ -74,8 +74,8 @@ features: t.Fatalf("loadConfig returned error: %v", err) } - if cfg.Brain.Port != 9231 { - t.Errorf("expected port 9231, got %d", cfg.Brain.Port) + if cfg.Haxen.Port != 9231 { + t.Errorf("expected port 9231, got %d", cfg.Haxen.Port) } if cfg.UI.Enabled { t.Error("expected UI disabled from config") @@ -115,7 +115,7 @@ func TestBuildUI_RunsInstallAndBuild(t *testing.T) { SourcePath: dir, DistPath: filepath.Join(dir, "dist"), }, - Brain: config.BrainConfig{Port: 8081}, + Haxen: config.HaxenConfig{Port: 8081}, } var mu sync.Mutex @@ -132,7 +132,7 @@ func TestBuildUI_RunsInstallAndBuild(t *testing.T) { t.Errorf("unexpected command dir %s", dir) } // Ensure environment includes proxy - expectedPrefix := fmt.Sprintf("VITE_API_PROXY_TARGET=http://localhost:%d", cfg.Brain.Port) + expectedPrefix := fmt.Sprintf("VITE_API_PROXY_TARGET=http://localhost:%d", cfg.Haxen.Port) found := false for _, envVar := range env { if envVar == expectedPrefix { @@ -184,7 +184,7 @@ func TestBuildUI_CommandError(t *testing.T) { func TestRunServer_AppliesFlagOverrides(t *testing.T) { cfg := &config.Config{ - Brain: config.BrainConfig{Port: 4000}, + Haxen: config.HaxenConfig{Port: 4000}, UI: config.UIConfig{Enabled: true, Mode: "embedded"}, Features: config.FeatureConfig{DID: config.DIDConfig{ VCRequirements: config.VCRequirements{ @@ -194,21 +194,21 @@ func TestRunServer_AppliesFlagOverrides(t *testing.T) { } loadOrig := loadConfigFunc - newOrig := newBrainServerFunc + newOrig := newHaxenServerFunc buildOrig := buildUIFunc openOrig := openBrowserFunc sleepOrig := sleepFunc waitOrig := waitForShutdownFunc - startOrig := startBrainServerFunc + startOrig := startHaxenServerFunc defer func() { loadConfigFunc = loadOrig - newBrainServerFunc = newOrig + newHaxenServerFunc = newOrig buildUIFunc = buildOrig openBrowserFunc = openOrig sleepFunc = sleepOrig waitForShutdownFunc = waitOrig - startBrainServerFunc = startOrig + startHaxenServerFunc = startOrig }() loadConfigFunc = func(path string) (*config.Config, error) { @@ -219,9 +219,9 @@ func TestRunServer_AppliesFlagOverrides(t *testing.T) { } var gotCfg *config.Config - newBrainServerFunc = func(c *config.Config) (*server.BrainServer, error) { + newHaxenServerFunc = func(c *config.Config) (*server.HaxenServer, error) { gotCfg = c - return &server.BrainServer{}, nil + return &server.HaxenServer{}, nil } buildUIFunc = func(*config.Config) error { return nil } @@ -230,7 +230,7 @@ func TestRunServer_AppliesFlagOverrides(t *testing.T) { waitForShutdownFunc = func() {} started := make(chan struct{}) - startBrainServerFunc = func(*server.BrainServer) error { + startHaxenServerFunc = func(*server.HaxenServer) error { close(started) return nil } @@ -253,17 +253,17 @@ func TestRunServer_AppliesFlagOverrides(t *testing.T) { t.Fatalf("failed to set no-vc-execution: %v", err) } - t.Setenv("BRAIN_PORT", "12345") + t.Setenv("HAXEN_PORT", "12345") runServer(cmd, nil) <-started if gotCfg == nil { - t.Fatal("expected brain server creation to be invoked") + t.Fatal("expected haxen server creation to be invoked") } - if gotCfg.Brain.Port != 12345 { - t.Fatalf("expected env override port 12345, got %d", gotCfg.Brain.Port) + if gotCfg.Haxen.Port != 12345 { + t.Fatalf("expected env override port 12345, got %d", gotCfg.Haxen.Port) } if gotCfg.UI.Enabled { t.Fatal("backend-only flag should disable UI") @@ -275,7 +275,7 @@ func TestRunServer_AppliesFlagOverrides(t *testing.T) { func TestRunServer_OpensBrowserForDevUI(t *testing.T) { cfg := &config.Config{ - Brain: config.BrainConfig{Port: 8800}, + Haxen: config.HaxenConfig{Port: 8800}, UI: config.UIConfig{ Enabled: true, Mode: "dev", @@ -285,27 +285,27 @@ func TestRunServer_OpensBrowserForDevUI(t *testing.T) { } loadOrig := loadConfigFunc - newOrig := newBrainServerFunc + newOrig := newHaxenServerFunc openOrig := openBrowserFunc sleepOrig := sleepFunc waitOrig := waitForShutdownFunc - startOrig := startBrainServerFunc + startOrig := startHaxenServerFunc defer func() { loadConfigFunc = loadOrig - newBrainServerFunc = newOrig + newHaxenServerFunc = newOrig openBrowserFunc = openOrig sleepFunc = sleepOrig waitForShutdownFunc = waitOrig - startBrainServerFunc = startOrig + startHaxenServerFunc = startOrig }() loadConfigFunc = func(string) (*config.Config, error) { return cfg, nil } - newBrainServerFunc = func(*config.Config) (*server.BrainServer, error) { return &server.BrainServer{}, nil } + newHaxenServerFunc = func(*config.Config) (*server.HaxenServer, error) { return &server.HaxenServer{}, nil } sleepFunc = func(time.Duration) {} waitForShutdownFunc = func() {} started := make(chan struct{}) - startBrainServerFunc = func(*server.BrainServer) error { + startHaxenServerFunc = func(*server.HaxenServer) error { close(started) return nil } diff --git a/control-plane/cmd/brain/main.go b/control-plane/cmd/haxen/main.go similarity index 81% rename from control-plane/cmd/brain/main.go rename to control-plane/cmd/haxen/main.go index a36fb3a1..8af26439 100644 --- a/control-plane/cmd/brain/main.go +++ b/control-plane/cmd/haxen/main.go @@ -1,12 +1,12 @@ package main import ( - "github.com/your-org/brain/control-plane/internal/cli" - "github.com/your-org/brain/control-plane/internal/config" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/internal/server" - "github.com/your-org/brain/control-plane/internal/utils" - "github.com/your-org/brain/control-plane/web/client" + "github.com/your-org/haxen/control-plane/internal/cli" + "github.com/your-org/haxen/control-plane/internal/config" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/server" + "github.com/your-org/haxen/control-plane/internal/utils" + "github.com/your-org/haxen/control-plane/web/client" "fmt" "log" "os" @@ -31,7 +31,7 @@ func main() { // runServer contains the server startup logic for unified CLI func runServer(cmd *cobra.Command, args []string) { - logger.Logger.Debug().Msg("Brain server starting...") + logger.Logger.Debug().Msg("Haxen server starting...") // Load configuration with better defaults cfgFilePath, _ := cmd.Flags().GetString("config") @@ -43,13 +43,13 @@ func runServer(cmd *cobra.Command, args []string) { // Override port from flag if provided if cmd.Flags().Lookup("port").Changed { port, _ := cmd.Flags().GetInt("port") - cfg.Brain.Port = port + cfg.Haxen.Port = port } // Override from environment variables - if envPort := os.Getenv("BRAIN_PORT"); envPort != "" { + if envPort := os.Getenv("HAXEN_PORT"); envPort != "" { if port, err := strconv.Atoi(envPort); err == nil { - cfg.Brain.Port = port + cfg.Haxen.Port = port } } @@ -62,7 +62,7 @@ func runServer(cmd *cobra.Command, args []string) { } if !storageModeExplicit { - if envMode := os.Getenv("BRAIN_STORAGE_MODE"); envMode != "" { + if envMode := os.Getenv("HAXEN_STORAGE_MODE"); envMode != "" { cfg.Storage.Mode = envMode } } @@ -72,9 +72,9 @@ func runServer(cmd *cobra.Command, args []string) { postgresURL, _ = cmd.Flags().GetString("postgres-url") } if postgresURL == "" { - if env := os.Getenv("BRAIN_POSTGRES_URL"); env != "" { + if env := os.Getenv("HAXEN_POSTGRES_URL"); env != "" { postgresURL = env - } else if env := os.Getenv("BRAIN_STORAGE_POSTGRES_URL"); env != "" { + } else if env := os.Getenv("HAXEN_STORAGE_POSTGRES_URL"); env != "" { postgresURL = env } } @@ -87,24 +87,24 @@ func runServer(cmd *cobra.Command, args []string) { } } - if env := os.Getenv("BRAIN_STORAGE_POSTGRES_HOST"); env != "" { + if env := os.Getenv("HAXEN_STORAGE_POSTGRES_HOST"); env != "" { cfg.Storage.Postgres.Host = env } - if env := os.Getenv("BRAIN_STORAGE_POSTGRES_PORT"); env != "" { + if env := os.Getenv("HAXEN_STORAGE_POSTGRES_PORT"); env != "" { if port, err := strconv.Atoi(env); err == nil { cfg.Storage.Postgres.Port = port } } - if env := os.Getenv("BRAIN_STORAGE_POSTGRES_DATABASE"); env != "" { + if env := os.Getenv("HAXEN_STORAGE_POSTGRES_DATABASE"); env != "" { cfg.Storage.Postgres.Database = env } - if env := os.Getenv("BRAIN_STORAGE_POSTGRES_USER"); env != "" { + if env := os.Getenv("HAXEN_STORAGE_POSTGRES_USER"); env != "" { cfg.Storage.Postgres.User = env } - if env := os.Getenv("BRAIN_STORAGE_POSTGRES_PASSWORD"); env != "" { + if env := os.Getenv("HAXEN_STORAGE_POSTGRES_PASSWORD"); env != "" { cfg.Storage.Postgres.Password = env } - if env := os.Getenv("BRAIN_STORAGE_POSTGRES_SSLMODE"); env != "" { + if env := os.Getenv("HAXEN_STORAGE_POSTGRES_SSLMODE"); env != "" { cfg.Storage.Postgres.SSLMode = env } @@ -142,17 +142,17 @@ func runServer(cmd *cobra.Command, args []string) { fmt.Println("UI is already embedded in binary, skipping build.") } - // Create Brain server instance - brainServer, err := server.NewBrainServer(cfg) + // Create Haxen server instance + haxenServer, err := server.NewHaxenServer(cfg) if err != nil { - log.Fatalf("Failed to create Brain server: %v", err) + log.Fatalf("Failed to create Haxen server: %v", err) } // Start the server in a goroutine so we can open the browser go func() { - fmt.Printf("Brain server attempting to start on port %d...\n", cfg.Brain.Port) - if err := brainServer.Start(); err != nil { - log.Fatalf("Failed to start Brain server: %v", err) + fmt.Printf("Haxen server attempting to start on port %d...\n", cfg.Haxen.Port) + if err := haxenServer.Start(); err != nil { + log.Fatalf("Failed to start Haxen server: %v", err) } }() @@ -161,7 +161,7 @@ func runServer(cmd *cobra.Command, args []string) { openBrowserFlag, _ := cmd.Flags().GetBool("open") if cfg.UI.Enabled && openBrowserFlag && !backendOnly { - uiTargetURL := fmt.Sprintf("http://localhost:%d", cfg.Brain.Port) + uiTargetURL := fmt.Sprintf("http://localhost:%d", cfg.Haxen.Port) if cfg.UI.Mode == "dev" { // Use configured dev port or environment variable devPort := cfg.UI.DevPort @@ -179,7 +179,7 @@ func runServer(cmd *cobra.Command, args []string) { openBrowser(uiTargetURL) } - fmt.Printf("Brain server running on http://localhost:%d\n", cfg.Brain.Port) + fmt.Printf("Haxen server running on http://localhost:%d\n", cfg.Haxen.Port) fmt.Printf("Press Ctrl+C to exit.\n") // Keep main goroutine alive select {} @@ -188,7 +188,7 @@ func runServer(cmd *cobra.Command, args []string) { // loadConfig loads configuration with sensible defaults for user experience func loadConfig(configFile string) (*config.Config, error) { // Set environment variable prefixes - viper.SetEnvPrefix("BRAIN") + viper.SetEnvPrefix("HAXEN") viper.AutomaticEnv() // Get the directory where the binary is located for UI paths @@ -203,16 +203,16 @@ func loadConfig(configFile string) (*config.Config, error) { viper.SetConfigFile(configFile) } else { // Check for config file path from environment - if envConfigFile := os.Getenv("BRAIN_CONFIG_FILE"); envConfigFile != "" { + if envConfigFile := os.Getenv("HAXEN_CONFIG_FILE"); envConfigFile != "" { viper.SetConfigFile(envConfigFile) } else { // Look for config in user's home directory first, then relative to exec dir, then local homeDir, _ := os.UserHomeDir() - viper.AddConfigPath(filepath.Join(homeDir, ".brain")) + viper.AddConfigPath(filepath.Join(homeDir, ".haxen")) viper.AddConfigPath(filepath.Join(execDir, "config")) viper.AddConfigPath("./config") viper.AddConfigPath(".") - viper.SetConfigName("brain") + viper.SetConfigName("haxen") viper.SetConfigType("yaml") } } @@ -231,8 +231,8 @@ func loadConfig(configFile string) (*config.Config, error) { } // Apply sensible defaults for user experience - if cfg.Brain.Port == 0 { - cfg.Brain.Port = 8080 + if cfg.Haxen.Port == 0 { + cfg.Haxen.Port = 8080 } // Enable UI by default unless explicitly disabled if cfg.UI.Mode == "" { @@ -248,8 +248,8 @@ func loadConfig(configFile string) (*config.Config, error) { if cfg.UI.SourcePath == "" { candidateSourcePaths := []string{ filepath.Join(execDir, "web", "client"), - filepath.Join(filepath.Dir(execDir), "apps", "platform", "brain", "web", "client"), - filepath.Join("apps", "platform", "brain", "web", "client"), + filepath.Join(filepath.Dir(execDir), "apps", "platform", "haxen", "web", "client"), + filepath.Join("apps", "platform", "haxen", "web", "client"), filepath.Join("web", "client"), } for _, candidate := range candidateSourcePaths { @@ -266,8 +266,8 @@ func loadConfig(configFile string) (*config.Config, error) { candidateDistPaths := []string{ filepath.Join(cfg.UI.SourcePath, "dist"), filepath.Join(execDir, "web", "client", "dist"), - filepath.Join(filepath.Dir(execDir), "apps", "platform", "brain", "web", "client", "dist"), - filepath.Join("apps", "platform", "brain", "web", "client", "dist"), + filepath.Join(filepath.Dir(execDir), "apps", "platform", "haxen", "web", "client", "dist"), + filepath.Join("apps", "platform", "haxen", "web", "client", "dist"), filepath.Join("web", "client", "dist"), } for _, candidate := range candidateDistPaths { @@ -324,14 +324,14 @@ func loadConfig(configFile string) (*config.Config, error) { } cfg.Storage.Local.KVStorePath = kvPath } - // Ensure all Brain data directories exist + // Ensure all Haxen data directories exist if _, err := utils.EnsureDataDirectories(); err != nil { - return nil, fmt.Errorf("failed to create Brain data directories: %w", err) + return nil, fmt.Errorf("failed to create Haxen data directories: %w", err) } } - fmt.Printf("Loaded config - Storage mode: %s, Brain Port: %d, UI Mode: %s, UI Enabled: %t\n", - cfg.Storage.Mode, cfg.Brain.Port, cfg.UI.Mode, cfg.UI.Enabled) + fmt.Printf("Loaded config - Storage mode: %s, Haxen Port: %d, UI Mode: %s, UI Enabled: %t\n", + cfg.Storage.Mode, cfg.Haxen.Port, cfg.UI.Mode, cfg.UI.Enabled) return &cfg, nil } @@ -357,7 +357,7 @@ func buildUI(cfg *config.Config) error { buildEnv = append(buildEnv, fmt.Sprintf("VITE_BUILD_OUT_DIR=%s", filepath.Base(cfg.UI.DistPath))) } - buildEnv = append(buildEnv, fmt.Sprintf("VITE_API_PROXY_TARGET=http://localhost:%d", cfg.Brain.Port)) + buildEnv = append(buildEnv, fmt.Sprintf("VITE_API_PROXY_TARGET=http://localhost:%d", cfg.Haxen.Port)) // Install dependencies cmdInstall := exec.Command("npm", "install", "--force") diff --git a/control-plane/config/docker-perf.yaml b/control-plane/config/docker-perf.yaml index aaae4002..a56fac8a 100644 --- a/control-plane/config/docker-perf.yaml +++ b/control-plane/config/docker-perf.yaml @@ -1,4 +1,4 @@ -brain: +haxen: port: 8080 mode: "local" max_concurrent_requests: 1024 @@ -78,13 +78,13 @@ features: hash_sensitive_data: true keystore: type: "local" - path: "/var/brain/data/keys" + path: "/var/haxen/data/keys" encryption: "AES-256-GCM" backup_enabled: true backup_interval: "24h" data_directories: - brain_home: "/var/brain" + haxen_home: "/var/haxen" database_dir: "data" keys_dir: "data/keys" did_registries_dir: "data/did_registries" diff --git a/control-plane/config/brain.yaml b/control-plane/config/haxen.yaml similarity index 99% rename from control-plane/config/brain.yaml rename to control-plane/config/haxen.yaml index 2d0c057f..2a8c976c 100644 --- a/control-plane/config/brain.yaml +++ b/control-plane/config/haxen.yaml @@ -1,4 +1,4 @@ -brain: +haxen: port: 8080 mode: "local" max_concurrent_requests: 1024 diff --git a/control-plane/go.mod b/control-plane/go.mod index f7e654c2..df1789da 100644 --- a/control-plane/go.mod +++ b/control-plane/go.mod @@ -1,4 +1,4 @@ -module github.com/your-org/brain/control-plane +module github.com/your-org/haxen/control-plane go 1.23.0 diff --git a/control-plane/internal/application/container.go b/control-plane/internal/application/container.go index 542424f5..46061db0 100644 --- a/control-plane/internal/application/container.go +++ b/control-plane/internal/application/container.go @@ -1,23 +1,23 @@ package application import ( - "github.com/your-org/brain/control-plane/internal/cli/framework" - "github.com/your-org/brain/control-plane/internal/config" - "github.com/your-org/brain/control-plane/internal/core/services" - "github.com/your-org/brain/control-plane/internal/infrastructure/process" - "github.com/your-org/brain/control-plane/internal/infrastructure/storage" - didServices "github.com/your-org/brain/control-plane/internal/services" - storageInterface "github.com/your-org/brain/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/internal/cli/framework" + "github.com/your-org/haxen/control-plane/internal/config" + "github.com/your-org/haxen/control-plane/internal/core/services" + "github.com/your-org/haxen/control-plane/internal/infrastructure/process" + "github.com/your-org/haxen/control-plane/internal/infrastructure/storage" + didServices "github.com/your-org/haxen/control-plane/internal/services" + storageInterface "github.com/your-org/haxen/control-plane/internal/storage" "crypto/sha256" "encoding/hex" "path/filepath" ) // CreateServiceContainer creates and wires up all services for the CLI commands -func CreateServiceContainer(cfg *config.Config, brainHome string) *framework.ServiceContainer { +func CreateServiceContainer(cfg *config.Config, haxenHome string) *framework.ServiceContainer { // Create infrastructure components fileSystem := storage.NewFileSystemAdapter() - registryPath := filepath.Join(brainHome, "installed.json") + registryPath := filepath.Join(haxenHome, "installed.json") registryStorage := storage.NewLocalRegistryStorage(fileSystem, registryPath) processManager := process.NewProcessManager() portManager := process.NewPortManager() @@ -32,8 +32,8 @@ func CreateServiceContainer(cfg *config.Config, brainHome string) *framework.Ser } // Create services - packageService := services.NewPackageService(registryStorage, fileSystem, brainHome) - agentService := services.NewAgentService(processManager, portManager, registryStorage, nil, brainHome) // nil agentClient for now + packageService := services.NewPackageService(registryStorage, fileSystem, haxenHome) + agentService := services.NewAgentService(processManager, portManager, registryStorage, nil, haxenHome) // nil agentClient for now devService := services.NewDevService(processManager, portManager, fileSystem) // Create DID services if enabled @@ -69,10 +69,10 @@ func CreateServiceContainer(cfg *config.Config, brainHome string) *framework.Ser if keystoreService != nil && didRegistry != nil { didService = didServices.NewDIDService(&cfg.Features.DID, keystoreService, didRegistry) - // Generate brain server ID based on brain home directory - // This ensures each brain instance has a unique ID while being deterministic - brainServerID := generateBrainServerID(brainHome) - didService.Initialize(brainServerID) + // Generate haxen server ID based on haxen home directory + // This ensures each haxen instance has a unique ID while being deterministic + haxenServerID := generateHaxenServerID(haxenHome) + didService.Initialize(haxenServerID) // Create VC service with database storage (required) if storageProvider != nil { @@ -98,28 +98,28 @@ func CreateServiceContainer(cfg *config.Config, brainHome string) *framework.Ser } // CreateServiceContainerWithDefaults creates a service container with default configuration -func CreateServiceContainerWithDefaults(brainHome string) *framework.ServiceContainer { +func CreateServiceContainerWithDefaults(haxenHome string) *framework.ServiceContainer { // Use default config for now cfg := &config.Config{} // This will be enhanced when config is properly structured - return CreateServiceContainer(cfg, brainHome) + return CreateServiceContainer(cfg, haxenHome) } -// generateBrainServerID creates a deterministic brain server ID based on the brain home directory. -// This ensures each brain instance has a unique ID while being deterministic for the same installation. -func generateBrainServerID(brainHome string) string { - // Use the absolute path of brain home to generate a deterministic ID - absPath, err := filepath.Abs(brainHome) +// generateHaxenServerID creates a deterministic haxen server ID based on the haxen home directory. +// This ensures each haxen instance has a unique ID while being deterministic for the same installation. +func generateHaxenServerID(haxenHome string) string { + // Use the absolute path of haxen home to generate a deterministic ID + absPath, err := filepath.Abs(haxenHome) if err != nil { // Fallback to the original path if absolute path fails - absPath = brainHome + absPath = haxenHome } - // Create a hash of the brain home path to generate a unique but deterministic ID + // Create a hash of the haxen home path to generate a unique but deterministic ID hash := sha256.Sum256([]byte(absPath)) - // Use first 16 characters of the hex hash as the brain server ID + // Use first 16 characters of the hex hash as the haxen server ID // This provides uniqueness while keeping the ID manageable - brainServerID := hex.EncodeToString(hash[:])[:16] + haxenServerID := hex.EncodeToString(hash[:])[:16] - return brainServerID + return haxenServerID } diff --git a/control-plane/internal/application/container_test.go b/control-plane/internal/application/container_test.go index 5f527fba..d47b46d7 100644 --- a/control-plane/internal/application/container_test.go +++ b/control-plane/internal/application/container_test.go @@ -6,17 +6,17 @@ import ( "strings" "testing" - "github.com/your-org/brain/control-plane/internal/config" - storagecfg "github.com/your-org/brain/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/internal/config" + storagecfg "github.com/your-org/haxen/control-plane/internal/storage" ) func TestCreateServiceContainerWithoutDID(t *testing.T) { t.Parallel() - brainHome := t.TempDir() + haxenHome := t.TempDir() cfg := &config.Config{} - container := CreateServiceContainer(cfg, brainHome) + container := CreateServiceContainer(cfg, haxenHome) if container.PackageService == nil || container.AgentService == nil || container.DevService == nil { t.Fatalf("expected core services to be initialised") @@ -29,13 +29,13 @@ func TestCreateServiceContainerWithoutDID(t *testing.T) { func TestCreateServiceContainerDIDWithoutStorageFallback(t *testing.T) { t.Parallel() - brainHome := t.TempDir() + haxenHome := t.TempDir() cfg := &config.Config{} cfg.Features.DID.Enabled = true - cfg.Features.DID.Keystore.Path = filepath.Join(brainHome, "keys") + cfg.Features.DID.Keystore.Path = filepath.Join(haxenHome, "keys") cfg.Storage.Mode = "invalid" - container := CreateServiceContainer(cfg, brainHome) + container := CreateServiceContainer(cfg, haxenHome) if container.DIDService != nil || container.VCService != nil { t.Fatalf("expected DID services to remain nil when storage initialisation fails") @@ -45,15 +45,15 @@ func TestCreateServiceContainerDIDWithoutStorageFallback(t *testing.T) { func TestCreateServiceContainerWithLocalDID(t *testing.T) { t.Parallel() - brainHome := t.TempDir() + haxenHome := t.TempDir() cfg := &config.Config{} cfg.Storage.Mode = "local" cfg.Storage.Local = storagecfg.LocalStorageConfig{ - DatabasePath: filepath.Join(brainHome, "brain.db"), - KVStorePath: filepath.Join(brainHome, "brain.bolt"), + DatabasePath: filepath.Join(haxenHome, "haxen.db"), + KVStorePath: filepath.Join(haxenHome, "haxen.bolt"), } cfg.Features.DID.Enabled = true - cfg.Features.DID.Keystore.Path = filepath.Join(brainHome, "keys") + cfg.Features.DID.Keystore.Path = filepath.Join(haxenHome, "keys") ctx := context.Background() probe := storagecfg.NewLocalStorage(storagecfg.LocalStorageConfig{}) @@ -71,7 +71,7 @@ func TestCreateServiceContainerWithLocalDID(t *testing.T) { t.Fatalf("failed to close probe storage: %v", err) } - container := CreateServiceContainer(cfg, brainHome) + container := CreateServiceContainer(cfg, haxenHome) if container.DIDService == nil { t.Fatalf("expected DID service to be initialised when configuration is valid") diff --git a/control-plane/internal/cli/add.go b/control-plane/internal/cli/add.go index 3a0ca80d..4ea6741c 100644 --- a/control-plane/internal/cli/add.go +++ b/control-plane/internal/cli/add.go @@ -7,8 +7,8 @@ import ( "strings" "time" - "github.com/your-org/brain/control-plane/internal/config" - "github.com/your-org/brain/control-plane/internal/mcp" + "github.com/your-org/haxen/control-plane/internal/config" + "github.com/your-org/haxen/control-plane/internal/mcp" "github.com/spf13/cobra" ) @@ -43,28 +43,28 @@ func NewAddCommand() *cobra.Command { cmd := &cobra.Command{ Use: "add [alias]", - Short: "Add dependencies to your Brain agent project", - Long: `Add dependencies to your Brain agent project. + Short: "Add dependencies to your Haxen agent project", + Long: `Add dependencies to your Haxen agent project. Supports adding MCP servers and regular agent packages with advanced configuration options. Examples: # Remote MCP servers (URL-based) - brain add --mcp --url https://github.com/modelcontextprotocol/server-github - brain add --mcp --url https://github.com/ferrislucas/iterm-mcp github-tools + haxen add --mcp --url https://github.com/modelcontextprotocol/server-github + haxen add --mcp --url https://github.com/ferrislucas/iterm-mcp github-tools # Local MCP servers with custom commands - brain add --mcp my-server --run "node server.js --port {{port}}" \ + haxen add --mcp my-server --run "node server.js --port {{port}}" \ --setup "npm install" --setup "npm run build" # Python MCP server with environment variables - brain add --mcp python-server --run "python server.py --port {{port}}" \ + haxen add --mcp python-server --run "python server.py --port {{port}}" \ --setup "pip install -r requirements.txt" \ --env "PYTHONPATH={{server_dir}}" \ --working-dir "./src" # Advanced configuration with health checks - brain add --mcp enterprise-server \ + haxen add --mcp enterprise-server \ --url https://github.com/company/mcp-server \ --run "node dist/server.js --port {{port}} --config {{config_file}}" \ --setup "npm install" --setup "npm run build" \ @@ -74,8 +74,8 @@ Examples: --tags "enterprise" --tags "production" # Regular agent packages (future) - brain add github.com/brain-helpers/email-utils - brain add github.com/openai/prompt-templates + haxen add github.com/haxen-helpers/email-utils + haxen add github.com/openai/prompt-templates Template Variables: {{port}} - Dynamically assigned port number @@ -121,7 +121,7 @@ func runAddCommandWithOptions(opts *MCPAddOptions, verbose bool) error { return fmt.Errorf("failed to get current directory: %w", err) } - if err := validateBrainProject(projectDir); err != nil { + if err := validateHaxenProject(projectDir); err != nil { return err } @@ -138,10 +138,10 @@ func runAddCommandWithOptions(opts *MCPAddOptions, verbose bool) error { return fmt.Errorf("only MCP server dependencies are currently supported. Use --mcp flag") } -func validateBrainProject(projectDir string) error { - brainYAMLPath := filepath.Join(projectDir, "brain.yaml") - if _, err := os.Stat(brainYAMLPath); os.IsNotExist(err) { - return fmt.Errorf("not a Brain project directory (brain.yaml not found)") +func validateHaxenProject(projectDir string) error { + haxenYAMLPath := filepath.Join(projectDir, "haxen.yaml") + if _, err := os.Stat(haxenYAMLPath); os.IsNotExist(err) { + return fmt.Errorf("not a Haxen project directory (haxen.yaml not found)") } return nil } @@ -159,12 +159,12 @@ type MCPAddCommand struct { // It performs initial processing and validation. func NewMCPAddCommand(projectDir string, opts *MCPAddOptions, verboseFlag bool) (*MCPAddCommand, error) { // Load application configuration - appCfg, err := config.LoadConfig(filepath.Join(projectDir, "brain.yaml")) + appCfg, err := config.LoadConfig(filepath.Join(projectDir, "haxen.yaml")) if err != nil { - // Fallback for safety, though brain.yaml should exist due to validateBrainProject - appCfg, err = config.LoadConfig("brain.yaml") + // Fallback for safety, though haxen.yaml should exist due to validateHaxenProject + appCfg, err = config.LoadConfig("haxen.yaml") if err != nil { - return nil, fmt.Errorf("failed to load brain configuration: %w. Ensure brain.yaml exists", err) + return nil, fmt.Errorf("failed to load haxen configuration: %w. Ensure haxen.yaml exists", err) } } @@ -304,8 +304,8 @@ func (cmd *MCPAddCommand) Execute() error { fmt.Printf(" %s Capabilities discovery and skill generation handled by manager\n", Gray(StatusInfo)) fmt.Printf("\n%s %s\n", Blue("→"), Bold("Next steps:")) - fmt.Printf(" %s Start the MCP server: %s\n", Gray("1."), Cyan(fmt.Sprintf("brain mcp start %s", mcpServerCfg.Alias))) - fmt.Printf(" %s Check status: %s\n", Gray("2."), Cyan("brain mcp status")) + fmt.Printf(" %s Start the MCP server: %s\n", Gray("1."), Cyan(fmt.Sprintf("haxen mcp start %s", mcpServerCfg.Alias))) + fmt.Printf(" %s Check status: %s\n", Gray("2."), Cyan("haxen mcp status")) fmt.Printf(" %s Use MCP tools as regular skills: %s\n", Gray("3."), Cyan(fmt.Sprintf("await app.call(\"%s_\", ...)", mcpServerCfg.Alias))) fmt.Printf(" %s Generated skill file: %s\n", Gray("4."), Gray(fmt.Sprintf("skills/mcp_%s.py", mcpServerCfg.Alias))) @@ -316,7 +316,7 @@ func (cmd *MCPAddCommand) Execute() error { // func addMCPServer(projectDir string, opts *MCPAddOptions, verbose bool) error { // fmt.Printf("Adding MCP server: %s\n", Bold(opts.Source)) // -// appCfg, err := config.LoadConfig(filepath.Join(projectDir, "brain.yaml")) +// appCfg, err := config.LoadConfig(filepath.Join(projectDir, "haxen.yaml")) // The orphaned code block that started with "if err != nil {" and was a remnant // of the original addMCPServer function body has been removed by this replacement. // The logic is now consolidated within MCPAddCommand.Execute(). diff --git a/control-plane/internal/cli/commands/dev.go b/control-plane/internal/cli/commands/dev.go index accf7b6a..f1419238 100644 --- a/control-plane/internal/cli/commands/dev.go +++ b/control-plane/internal/cli/commands/dev.go @@ -4,8 +4,8 @@ import ( "fmt" "github.com/spf13/cobra" - "github.com/your-org/brain/control-plane/internal/cli/framework" - "github.com/your-org/brain/control-plane/internal/core/domain" + "github.com/your-org/haxen/control-plane/internal/cli/framework" + "github.com/your-org/haxen/control-plane/internal/core/domain" ) type DevCommand struct { @@ -25,7 +25,7 @@ func (cmd *DevCommand) GetName() string { } func (cmd *DevCommand) GetDescription() string { - return "Run a Brain agent package in development mode" + return "Run a Haxen agent package in development mode" } func (cmd *DevCommand) BuildCobraCommand() *cobra.Command { @@ -36,19 +36,19 @@ func (cmd *DevCommand) BuildCobraCommand() *cobra.Command { cobraCmd := &cobra.Command{ Use: "dev [path]", Short: cmd.GetDescription(), - Long: `Run a Brain agent package in development mode from the current directory or specified path. + Long: `Run a Haxen agent package in development mode from the current directory or specified path. This command is designed for local development and testing. It will: -- Look for brain.yaml in the current directory (or specified path) +- Look for haxen.yaml in the current directory (or specified path) - Start the agent without requiring installation - Provide verbose logging for development - Optionally watch for file changes and auto-restart Examples: - brain dev # Run package in current directory - brain dev ./my-agent # Run package in specified directory - brain dev --port 8005 # Use specific port - brain dev --watch # Watch for changes and auto-restart`, + haxen dev # Run package in current directory + haxen dev ./my-agent # Run package in specified directory + haxen dev --port 8005 # Use specific port + haxen dev --watch # Watch for changes and auto-restart`, Args: cobra.MaximumNArgs(1), RunE: func(cobraCmd *cobra.Command, args []string) error { return cmd.execute(args, port, watch, verbose) @@ -71,7 +71,7 @@ func (cmd *DevCommand) execute(args []string, port int, watch, verbose bool) err packagePath = "." } - cmd.output.PrintHeader("🚀 Brain Development Mode") + cmd.output.PrintHeader("🚀 Haxen Development Mode") cmd.output.PrintInfo(fmt.Sprintf("Package path: %s", packagePath)) // Create dev options diff --git a/control-plane/internal/cli/commands/install.go b/control-plane/internal/cli/commands/install.go index d80431bd..7e351be5 100644 --- a/control-plane/internal/cli/commands/install.go +++ b/control-plane/internal/cli/commands/install.go @@ -3,8 +3,8 @@ package commands import ( "fmt" "github.com/spf13/cobra" - "github.com/your-org/brain/control-plane/internal/cli/framework" - "github.com/your-org/brain/control-plane/internal/core/domain" + "github.com/your-org/haxen/control-plane/internal/cli/framework" + "github.com/your-org/haxen/control-plane/internal/core/domain" ) // InstallCommand implements the install command using the new framework @@ -28,7 +28,7 @@ func (cmd *InstallCommand) GetName() string { // GetDescription returns the command description func (cmd *InstallCommand) GetDescription() string { - return "Install a Brain agent node package for local use" + return "Install a Haxen agent node package for local use" } // BuildCobraCommand builds the Cobra command @@ -39,17 +39,17 @@ func (cmd *InstallCommand) BuildCobraCommand() *cobra.Command { cobraCmd := &cobra.Command{ Use: "install ", Short: cmd.GetDescription(), - Long: `Install a Brain agent node package for local use. + Long: `Install a Haxen agent node package for local use. The package can be: - A local directory path - A GitHub repository URL -- A package name from the Brain registry +- A package name from the Haxen registry Examples: - brain install ./my-agent - brain install https://github.com/user/agent-repo - brain install agent-name`, + haxen install ./my-agent + haxen install https://github.com/user/agent-repo + haxen install agent-name`, Args: cobra.ExactArgs(1), RunE: func(cobraCmd *cobra.Command, args []string) error { // Update output formatter with verbose setting @@ -66,7 +66,7 @@ Examples: // execute performs the actual installation func (cmd *InstallCommand) execute(packagePath string, force, verbose bool) error { - cmd.output.PrintHeader("Installing Brain Package") + cmd.output.PrintHeader("Installing Haxen Package") cmd.output.PrintInfo(fmt.Sprintf("Package: %s", packagePath)) if verbose { diff --git a/control-plane/internal/cli/commands/run.go b/control-plane/internal/cli/commands/run.go index 6a4a1fb7..8fa13418 100644 --- a/control-plane/internal/cli/commands/run.go +++ b/control-plane/internal/cli/commands/run.go @@ -3,8 +3,8 @@ package commands import ( "fmt" "github.com/spf13/cobra" - "github.com/your-org/brain/control-plane/internal/cli/framework" - "github.com/your-org/brain/control-plane/internal/core/domain" + "github.com/your-org/haxen/control-plane/internal/cli/framework" + "github.com/your-org/haxen/control-plane/internal/core/domain" ) // RunCommand implements the run command using the new framework @@ -28,7 +28,7 @@ func (cmd *RunCommand) GetName() string { // GetDescription returns the command description func (cmd *RunCommand) GetDescription() string { - return "Run an installed Brain agent node package" + return "Run an installed Haxen agent node package" } // BuildCobraCommand builds the Cobra command @@ -40,15 +40,15 @@ func (cmd *RunCommand) BuildCobraCommand() *cobra.Command { cobraCmd := &cobra.Command{ Use: "run ", Short: cmd.GetDescription(), - Long: `Start an installed Brain agent node package in the background. + Long: `Start an installed Haxen agent node package in the background. The agent node will be assigned an available port and registered with -the Brain server if available. +the Haxen server if available. Examples: - brain run email-helper - brain run data-analyzer --port 8005 - brain run my-agent --detach=false`, + haxen run email-helper + haxen run data-analyzer --port 8005 + haxen run my-agent --detach=false`, Args: cobra.ExactArgs(1), RunE: func(cobraCmd *cobra.Command, args []string) error { // Update output formatter with verbose setting @@ -66,7 +66,7 @@ Examples: // execute performs the actual agent execution func (cmd *RunCommand) execute(agentName string, port int, detach, verbose bool) error { - cmd.output.PrintHeader("Running Brain Agent") + cmd.output.PrintHeader("Running Haxen Agent") cmd.output.PrintInfo(fmt.Sprintf("Agent: %s", agentName)) if verbose { @@ -118,8 +118,8 @@ func (cmd *RunCommand) execute(agentName string, port int, detach, verbose bool) if detach { cmd.output.PrintInfo("Agent is running in the background") - cmd.output.PrintInfo("Use 'brain stop " + agentName + "' to stop the agent") - cmd.output.PrintInfo("Use 'brain logs " + agentName + "' to view logs") + cmd.output.PrintInfo("Use 'haxen stop " + agentName + "' to stop the agent") + cmd.output.PrintInfo("Use 'haxen logs " + agentName + "' to view logs") } return nil diff --git a/control-plane/internal/cli/config.go b/control-plane/internal/cli/config.go index 97a8cc33..c5d67160 100644 --- a/control-plane/internal/cli/config.go +++ b/control-plane/internal/cli/config.go @@ -13,7 +13,7 @@ import ( "golang.org/x/term" "gopkg.in/yaml.v3" - "github.com/your-org/brain/control-plane/internal/packages" + "github.com/your-org/haxen/control-plane/internal/packages" ) var ( @@ -26,18 +26,18 @@ var ( func NewConfigCommand() *cobra.Command { cmd := &cobra.Command{ Use: "config ", - Short: "Configure environment variables for an installed Brain agent package", - Long: `Configure environment variables for an installed Brain agent package. + Short: "Configure environment variables for an installed Haxen agent package", + Long: `Configure environment variables for an installed Haxen agent package. This command allows you to set up required and optional environment variables for installed packages. It will prompt for each variable and create a .env file in the package directory that will be loaded when the agent runs. Examples: - brain config my-agent # Interactive configuration - brain config my-agent --list # List current configuration - brain config my-agent --set KEY=VALUE # Set specific variable - brain config my-agent --unset KEY # Remove variable`, + haxen config my-agent # Interactive configuration + haxen config my-agent --list # List current configuration + haxen config my-agent --set KEY=VALUE # Set specific variable + haxen config my-agent --unset KEY # Remove variable`, Args: cobra.ExactArgs(1), Run: runConfigCommand, } @@ -51,10 +51,10 @@ Examples: func runConfigCommand(cmd *cobra.Command, args []string) { packageName := args[0] - brainHome := getBrainHomeDir() + haxenHome := getHaxenHomeDir() configManager := &PackageConfigManager{ - BrainHome: brainHome, + HaxenHome: haxenHome, } if configList { @@ -97,7 +97,7 @@ func runConfigCommand(cmd *cobra.Command, args []string) { // PackageConfigManager handles environment configuration for packages type PackageConfigManager struct { - BrainHome string + HaxenHome string } // InteractiveConfig runs interactive configuration for a package @@ -159,7 +159,7 @@ func (pcm *PackageConfigManager) InteractiveConfig(packageName string) error { } fmt.Printf("✅ Environment configuration saved to: %s/.env\n", packagePath) - fmt.Printf("💡 Run 'brain run %s' to start the agent with these settings\n", packageName) + fmt.Printf("💡 Run 'haxen run %s' to start the agent with these settings\n", packageName) return nil } @@ -361,7 +361,7 @@ func (pcm *PackageConfigManager) UnsetVariable(packageName, key string) error { // loadPackageMetadata loads package metadata and returns the package path func (pcm *PackageConfigManager) loadPackageMetadata(packageName string) (*packages.PackageMetadata, string, error) { // Load registry to get package path - registryPath := filepath.Join(pcm.BrainHome, "installed.yaml") + registryPath := filepath.Join(pcm.HaxenHome, "installed.yaml") registry := &packages.InstallationRegistry{ Installed: make(map[string]packages.InstalledPackage), } @@ -378,7 +378,7 @@ func (pcm *PackageConfigManager) loadPackageMetadata(packageName string) (*packa } // Load package metadata - metadataPath := filepath.Join(installedPackage.Path, "brain-package.yaml") + metadataPath := filepath.Join(installedPackage.Path, "haxen-package.yaml") data, err := os.ReadFile(metadataPath) if err != nil { return nil, "", fmt.Errorf("failed to read package metadata: %w", err) @@ -433,8 +433,8 @@ func (pcm *PackageConfigManager) saveEnvFile(packagePath string, envVars map[str envPath := filepath.Join(packagePath, ".env") var lines []string - lines = append(lines, "# Environment variables for Brain agent") - lines = append(lines, "# Generated by 'brain config' command") + lines = append(lines, "# Environment variables for Haxen agent") + lines = append(lines, "# Generated by 'haxen config' command") lines = append(lines, "") for key, value := range envVars { diff --git a/control-plane/internal/cli/framework/command.go b/control-plane/internal/cli/framework/command.go index fa559901..63901878 100644 --- a/control-plane/internal/cli/framework/command.go +++ b/control-plane/internal/cli/framework/command.go @@ -2,9 +2,9 @@ package framework import ( "github.com/spf13/cobra" - "github.com/your-org/brain/control-plane/internal/core/interfaces" - "github.com/your-org/brain/control-plane/internal/services" - "github.com/your-org/brain/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/internal/core/interfaces" + "github.com/your-org/haxen/control-plane/internal/services" + "github.com/your-org/haxen/control-plane/internal/storage" ) // Command represents a CLI command that can be built into a Cobra command diff --git a/control-plane/internal/cli/framework/output.go b/control-plane/internal/cli/framework/output.go index 6f7fd51c..979e5190 100644 --- a/control-plane/internal/cli/framework/output.go +++ b/control-plane/internal/cli/framework/output.go @@ -35,7 +35,7 @@ func (o *OutputFormatter) PrintWarning(message string) { fmt.Printf("⚠️ %s\n", color.YellowString(message)) } -// PrintHeader prints a header message with brain emoji and bold text +// PrintHeader prints a header message with haxen emoji and bold text func (o *OutputFormatter) PrintHeader(message string) { fmt.Printf("\n%s %s\n", color.CyanString("🧠"), color.New(color.Bold).Sprint(message)) } diff --git a/control-plane/internal/cli/init.go b/control-plane/internal/cli/init.go index 7dadd61a..205e1090 100644 --- a/control-plane/internal/cli/init.go +++ b/control-plane/internal/cli/init.go @@ -12,8 +12,8 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/internal/templates" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/templates" ) // NewInitCommand builds a fresh Cobra command for initializing a new agent project. @@ -23,18 +23,18 @@ func NewInitCommand() *cobra.Command { cmd := &cobra.Command{ Use: "init [project-name]", - Short: "Initialize a new Brain agent project", - Long: `Initialize a new Brain agent project with a predefined + Short: "Initialize a new Haxen agent project", + Long: `Initialize a new Haxen agent project with a predefined directory structure and essential files. This command sets up a new project, including: - Python project structure (pyproject.toml, main.py, agent/...) - Basic agent implementation with example reasoner/skill - README.md, LICENSE, and .gitignore files - - Configuration for connecting to the Brain control plane + - Configuration for connecting to the Haxen control plane Example: - brain init my-new-agent --author "John Doe" --email "john.doe@example.com"`, + haxen init my-new-agent --author "John Doe" --email "john.doe@example.com"`, Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { projectName := args[0] @@ -118,8 +118,8 @@ func NewInitCommand() *cobra.Command { fmt.Printf("\nNext steps:\n") PrintInfo(fmt.Sprintf("cd %s", projectName)) - PrintInfo("brain install .") - PrintInfo(fmt.Sprintf("brain run %s", projectName)) + PrintInfo("haxen install .") + PrintInfo(fmt.Sprintf("haxen run %s", projectName)) }, } diff --git a/control-plane/internal/cli/list.go b/control-plane/internal/cli/list.go index c3643463..f1d89e51 100644 --- a/control-plane/internal/cli/list.go +++ b/control-plane/internal/cli/list.go @@ -7,20 +7,20 @@ import ( "github.com/spf13/cobra" "gopkg.in/yaml.v3" - "github.com/your-org/brain/control-plane/internal/packages" + "github.com/your-org/haxen/control-plane/internal/packages" ) // NewListCommand creates the list command func NewListCommand() *cobra.Command { cmd := &cobra.Command{ Use: "list", - Short: "List installed Brain agent node packages", - Long: `Display all installed Brain agent node packages with their status. + Short: "List installed Haxen agent node packages", + Long: `Display all installed Haxen agent node packages with their status. Shows package name, version, status (running/stopped), and port if running. Examples: - brain list`, + haxen list`, Run: runListCommand, } @@ -28,8 +28,8 @@ Examples: } func runListCommand(cmd *cobra.Command, args []string) { - brainHome := getBrainHomeDir() - registryPath := filepath.Join(brainHome, "installed.yaml") + haxenHome := getHaxenHomeDir() + registryPath := filepath.Join(haxenHome, "installed.yaml") // Load registry registry := &packages.InstallationRegistry{ @@ -42,7 +42,7 @@ func runListCommand(cmd *cobra.Command, args []string) { if len(registry.Installed) == 0 { fmt.Println("📦 No agent node packages installed") - fmt.Println("💡 Install packages with: brain install ") + fmt.Println("💡 Install packages with: haxen install ") return } @@ -69,7 +69,7 @@ func runListCommand(cmd *cobra.Command, args []string) { } fmt.Println("💡 Commands:") - fmt.Println(" brain run - Start an agent node") - fmt.Println(" brain stop - Stop a running agent node") - fmt.Println(" brain logs - View agent node logs") + fmt.Println(" haxen run - Start an agent node") + fmt.Println(" haxen stop - Stop a running agent node") + fmt.Println(" haxen logs - View agent node logs") } diff --git a/control-plane/internal/cli/logs.go b/control-plane/internal/cli/logs.go index f0793ad7..4c55dcc0 100644 --- a/control-plane/internal/cli/logs.go +++ b/control-plane/internal/cli/logs.go @@ -8,8 +8,8 @@ import ( "github.com/spf13/cobra" "gopkg.in/yaml.v3" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/internal/packages" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/packages" ) var ( @@ -21,14 +21,14 @@ var ( func NewLogsCommand() *cobra.Command { cmd := &cobra.Command{ Use: "logs ", - Short: "View logs for a Brain agent node", - Long: `Display logs for an installed Brain agent node package. + Short: "View logs for a Haxen agent node", + Long: `Display logs for an installed Haxen agent node package. Shows the most recent log entries from the agent node's log file. Examples: - brain logs email-helper - brain logs data-analyzer --follow`, + haxen logs email-helper + haxen logs data-analyzer --follow`, Args: cobra.ExactArgs(1), Run: runLogsCommand, } @@ -43,7 +43,7 @@ func runLogsCommand(cmd *cobra.Command, args []string) { agentNodeName := args[0] logViewer := &LogViewer{ - BrainHome: getBrainHomeDir(), + HaxenHome: getHaxenHomeDir(), Follow: logsFollow, Tail: logsTail, } @@ -56,7 +56,7 @@ func runLogsCommand(cmd *cobra.Command, args []string) { // LogViewer handles viewing agent node logs type LogViewer struct { - BrainHome string + HaxenHome string Follow bool Tail int } @@ -64,7 +64,7 @@ type LogViewer struct { // ViewLogs displays logs for an agent node func (lv *LogViewer) ViewLogs(agentNodeName string) error { // Load registry to get log file path - registryPath := filepath.Join(lv.BrainHome, "installed.yaml") + registryPath := filepath.Join(lv.HaxenHome, "installed.yaml") registry := &packages.InstallationRegistry{ Installed: make(map[string]packages.InstalledPackage), } diff --git a/control-plane/internal/cli/mcp.go b/control-plane/internal/cli/mcp.go index 1c4726fa..4c4881ee 100644 --- a/control-plane/internal/cli/mcp.go +++ b/control-plane/internal/cli/mcp.go @@ -6,8 +6,8 @@ import ( "path/filepath" "strings" - "github.com/your-org/brain/control-plane/internal/config" // Ensured this import is correct - "github.com/your-org/brain/control-plane/internal/mcp" + "github.com/your-org/haxen/control-plane/internal/config" // Ensured this import is correct + "github.com/your-org/haxen/control-plane/internal/mcp" "github.com/spf13/cobra" ) @@ -16,8 +16,8 @@ import ( func NewMCPCommand() *cobra.Command { cmd := &cobra.Command{ Use: "mcp", - Short: "Manage MCP servers in your Brain agent project", - Long: `Manage Model Context Protocol (MCP) servers in your Brain agent project. + Short: "Manage MCP servers in your Haxen agent project", + Long: `Manage Model Context Protocol (MCP) servers in your Haxen agent project. MCP servers provide external tools and resources that can be integrated into your agent.`, } @@ -54,15 +54,15 @@ func runMCPStatusCommand(cmd *cobra.Command, args []string) error { return fmt.Errorf("failed to get current directory: %w", err) } - if err := validateBrainProject(projectDir); err != nil { + if err := validateHaxenProject(projectDir); err != nil { return err } - cfg, err := config.LoadConfig(filepath.Join(projectDir, "brain.yaml")) + cfg, err := config.LoadConfig(filepath.Join(projectDir, "haxen.yaml")) if err != nil { - cfg, err = config.LoadConfig("brain.yaml") // Fallback + cfg, err = config.LoadConfig("haxen.yaml") // Fallback if err != nil { - return fmt.Errorf("failed to load brain configuration: %w", err) + return fmt.Errorf("failed to load haxen configuration: %w", err) } } manager := mcp.NewMCPManager(cfg, projectDir, verbose) @@ -75,7 +75,7 @@ func runMCPStatusCommand(cmd *cobra.Command, args []string) error { if len(servers) == 0 { PrintInfo("No MCP servers installed") - fmt.Printf("\n%s %s\n", Blue("→"), "Add an MCP server: brain add --mcp @modelcontextprotocol/server-github") + fmt.Printf("\n%s %s\n", Blue("→"), "Add an MCP server: haxen add --mcp @modelcontextprotocol/server-github") return nil } @@ -148,15 +148,15 @@ func runMCPStartCommand(cmd *cobra.Command, args []string) error { return fmt.Errorf("failed to get current directory: %w", err) } - if err := validateBrainProject(projectDir); err != nil { + if err := validateHaxenProject(projectDir); err != nil { return err } - cfg, err := config.LoadConfig(filepath.Join(projectDir, "brain.yaml")) + cfg, err := config.LoadConfig(filepath.Join(projectDir, "haxen.yaml")) if err != nil { - cfg, err = config.LoadConfig("brain.yaml") // Fallback + cfg, err = config.LoadConfig("haxen.yaml") // Fallback if err != nil { - return fmt.Errorf("failed to load brain configuration: %w", err) + return fmt.Errorf("failed to load haxen configuration: %w", err) } } manager := mcp.NewMCPManager(cfg, projectDir, verbose) @@ -194,15 +194,15 @@ func runMCPStopCommand(cmd *cobra.Command, args []string) error { return fmt.Errorf("failed to get current directory: %w", err) } - if err := validateBrainProject(projectDir); err != nil { + if err := validateHaxenProject(projectDir); err != nil { return err } - cfg, err := config.LoadConfig(filepath.Join(projectDir, "brain.yaml")) + cfg, err := config.LoadConfig(filepath.Join(projectDir, "haxen.yaml")) if err != nil { - cfg, err = config.LoadConfig("brain.yaml") // Fallback + cfg, err = config.LoadConfig("haxen.yaml") // Fallback if err != nil { - return fmt.Errorf("failed to load brain configuration: %w", err) + return fmt.Errorf("failed to load haxen configuration: %w", err) } } manager := mcp.NewMCPManager(cfg, projectDir, verbose) @@ -273,7 +273,7 @@ func runMCPLogsCommand(cmd *cobra.Command, args []string, follow bool, tail int) return fmt.Errorf("failed to get current directory: %w", err) } - if err := validateBrainProject(projectDir); err != nil { + if err := validateHaxenProject(projectDir); err != nil { return err } @@ -317,7 +317,7 @@ func NewMCPSkillsGenerateCommand() *cobra.Command { cmd := &cobra.Command{ Use: "generate [alias]", Short: "Generate skill files for MCP servers", - Long: `Generate Python skill files that wrap MCP tools as Brain skills.`, + Long: `Generate Python skill files that wrap MCP tools as Haxen skills.`, Args: cobra.MaximumNArgs(1), RunE: runMCPSkillsGenerateCommand, } @@ -333,7 +333,7 @@ func runMCPSkillsGenerateCommand(cmd *cobra.Command, args []string) error { return fmt.Errorf("failed to get current directory: %w", err) } - if err := validateBrainProject(projectDir); err != nil { + if err := validateHaxenProject(projectDir); err != nil { return err } @@ -391,7 +391,7 @@ func runMCPSkillsListCommand(cmd *cobra.Command, args []string) error { return fmt.Errorf("failed to get current directory: %w", err) } - if err := validateBrainProject(projectDir); err != nil { + if err := validateHaxenProject(projectDir); err != nil { return err } @@ -420,7 +420,7 @@ func runMCPSkillsListCommand(cmd *cobra.Command, args []string) error { fmt.Printf(" %s %s\n", Gray("File:"), entry.Name()) // Try to get server info - if cfg, err := config.LoadConfig(filepath.Join(projectDir, "brain.yaml")); err == nil { + if cfg, err := config.LoadConfig(filepath.Join(projectDir, "haxen.yaml")); err == nil { discovery := mcp.NewCapabilityDiscovery(cfg, projectDir) if capability, err := discovery.GetServerCapability(alias); err == nil { fmt.Printf(" %s %d tools available\n", Gray("Tools:"), len(capability.Tools)) @@ -430,7 +430,7 @@ func runMCPSkillsListCommand(cmd *cobra.Command, args []string) error { if skillCount == 0 { PrintInfo("No auto-generated MCP skills found") - fmt.Printf("\n%s %s\n", Blue("→"), "Generate skills: brain mcp skills generate") + fmt.Printf("\n%s %s\n", Blue("→"), "Generate skills: haxen mcp skills generate") } else { fmt.Printf("\n%s %d skill files found\n", Gray("Total:"), skillCount) } @@ -456,15 +456,15 @@ func runMCPSkillsRefreshCommand(cmd *cobra.Command, args []string) error { return fmt.Errorf("failed to get current directory: %w", err) } - if err := validateBrainProject(projectDir); err != nil { + if err := validateHaxenProject(projectDir); err != nil { return err } - cfg, err := config.LoadConfig(filepath.Join(projectDir, "brain.yaml")) + cfg, err := config.LoadConfig(filepath.Join(projectDir, "haxen.yaml")) if err != nil { - cfg, err = config.LoadConfig("brain.yaml") // Fallback + cfg, err = config.LoadConfig("haxen.yaml") // Fallback if err != nil { - return fmt.Errorf("failed to load brain configuration: %w", err) + return fmt.Errorf("failed to load haxen configuration: %w", err) } } manager := mcp.NewMCPManager(cfg, projectDir, verbose) @@ -521,15 +521,15 @@ func runMCPRemoveCommand(cmd *cobra.Command, args []string, force bool) error { return fmt.Errorf("failed to get current directory: %w", err) } - if err := validateBrainProject(projectDir); err != nil { + if err := validateHaxenProject(projectDir); err != nil { return err } - cfg, err := config.LoadConfig(filepath.Join(projectDir, "brain.yaml")) + cfg, err := config.LoadConfig(filepath.Join(projectDir, "haxen.yaml")) if err != nil { - cfg, err = config.LoadConfig("brain.yaml") // Fallback + cfg, err = config.LoadConfig("haxen.yaml") // Fallback if err != nil { - return fmt.Errorf("failed to load brain configuration: %w", err) + return fmt.Errorf("failed to load haxen configuration: %w", err) } } manager := mcp.NewMCPManager(cfg, projectDir, verbose) @@ -574,15 +574,15 @@ func runMCPDiscoverCommand(cmd *cobra.Command, args []string, refresh bool) erro return fmt.Errorf("failed to get current directory: %w", err) } - if err := validateBrainProject(projectDir); err != nil { + if err := validateHaxenProject(projectDir); err != nil { return err } - cfg, err := config.LoadConfig(filepath.Join(projectDir, "brain.yaml")) + cfg, err := config.LoadConfig(filepath.Join(projectDir, "haxen.yaml")) if err != nil { - cfg, err = config.LoadConfig("brain.yaml") // Fallback + cfg, err = config.LoadConfig("haxen.yaml") // Fallback if err != nil { - return fmt.Errorf("failed to load brain configuration: %w", err) + return fmt.Errorf("failed to load haxen configuration: %w", err) } } @@ -677,15 +677,15 @@ func runMCPMigrateCommand(cmd *cobra.Command, args []string) error { return fmt.Errorf("failed to get current directory: %w", err) } - if err := validateBrainProject(projectDir); err != nil { + if err := validateHaxenProject(projectDir); err != nil { return err } - cfg, err := config.LoadConfig(filepath.Join(projectDir, "brain.yaml")) + cfg, err := config.LoadConfig(filepath.Join(projectDir, "haxen.yaml")) if err != nil { - cfg, err = config.LoadConfig("brain.yaml") // Fallback + cfg, err = config.LoadConfig("haxen.yaml") // Fallback if err != nil { - return fmt.Errorf("failed to load brain configuration: %w", err) + return fmt.Errorf("failed to load haxen configuration: %w", err) } } diff --git a/control-plane/internal/cli/root.go b/control-plane/internal/cli/root.go index ca1555e5..c0845d00 100644 --- a/control-plane/internal/cli/root.go +++ b/control-plane/internal/cli/root.go @@ -4,10 +4,10 @@ import ( "fmt" "os" - "github.com/your-org/brain/control-plane/internal/application" - "github.com/your-org/brain/control-plane/internal/cli/commands" - "github.com/your-org/brain/control-plane/internal/config" - "github.com/your-org/brain/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/application" + "github.com/your-org/haxen/control-plane/internal/cli/commands" + "github.com/your-org/haxen/control-plane/internal/config" + "github.com/your-org/haxen/control-plane/internal/logger" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -24,12 +24,12 @@ var ( postgresURLFlag string ) -// NewRootCommand creates and returns the root Cobra command for the Brain CLI. +// NewRootCommand creates and returns the root Cobra command for the Haxen CLI. func NewRootCommand(runServerFunc func(cmd *cobra.Command, args []string)) *cobra.Command { RootCmd := &cobra.Command{ - Use: "brain", - Short: "Brain AI Agent Platform", - Long: `Brain is a comprehensive AI agent platform for building, managing, and deploying AI agent capabilities.`, + Use: "haxen", + Short: "Haxen AI Agent Platform", + Long: `Haxen is a comprehensive AI agent platform for building, managing, and deploying AI agent capabilities.`, PersistentPreRunE: func(cmd *cobra.Command, args []string) error { // Initialize logging based on verbose flag logger.InitLogger(verbose) @@ -41,14 +41,14 @@ func NewRootCommand(runServerFunc func(cmd *cobra.Command, args []string)) *cobr // Default to server mode when no subcommand is provided (backward compatibility) Run: runServerFunc, } - RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "Path to configuration file (e.g., config/brain.yaml)") + RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "Path to configuration file (e.g., config/haxen.yaml)") RootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "Enable verbose logging") // Flags for the server command (moved from main.go) RootCmd.PersistentFlags().BoolVar(&openBrowserFlag, "open", true, "Open browser to UI (if UI is enabled)") RootCmd.PersistentFlags().BoolVar(&uiDevFlag, "ui-dev", false, "Run with UI development server (proxies to backend)") RootCmd.PersistentFlags().BoolVar(&backendOnlyFlag, "backend-only", false, "Run only backend APIs, UI served separately") - RootCmd.PersistentFlags().IntVar(&portFlag, "port", 0, "Port for the brain server (overrides config if set)") + RootCmd.PersistentFlags().IntVar(&portFlag, "port", 0, "Port for the haxen server (overrides config if set)") RootCmd.PersistentFlags().BoolVar(&noVCExecution, "no-vc-execution", false, "Disable generating verifiable credentials for executions") RootCmd.PersistentFlags().StringVar(&storageModeFlag, "storage-mode", "", "Override the storage backend (local or postgres)") RootCmd.PersistentFlags().StringVar(&postgresURLFlag, "postgres-url", "", "PostgreSQL connection URL or DSN (implies --storage-mode=postgres)") @@ -60,7 +60,7 @@ func NewRootCommand(runServerFunc func(cmd *cobra.Command, args []string)) *cobr // Create service container for framework commands cfg := &config.Config{} // Use default config for now - services := application.CreateServiceContainer(cfg, getBrainHomeDir()) + services := application.CreateServiceContainer(cfg, getHaxenHomeDir()) // Add framework-based commands (migrated commands) installCommand := commands.NewInstallCommand(services) @@ -85,8 +85,8 @@ func NewRootCommand(runServerFunc func(cmd *cobra.Command, args []string)) *cobr // Add the server command serverCmd := &cobra.Command{ Use: "server", - Short: "Run the Brain AI Agent Platform server", - Long: `Starts the Brain AI Agent Platform server, providing API endpoints and UI.`, + Short: "Run the Haxen AI Agent Platform server", + Long: `Starts the Haxen AI Agent Platform server, providing API endpoints and UI.`, Run: runServerFunc, } RootCmd.AddCommand(serverCmd) @@ -103,7 +103,7 @@ func initConfig() { // Search config in current directory and "config" directory viper.AddConfigPath(".") viper.AddConfigPath("./config") - viper.SetConfigName("brain") + viper.SetConfigName("haxen") viper.SetConfigType("yaml") } diff --git a/control-plane/internal/cli/root_test.go b/control-plane/internal/cli/root_test.go index f6908107..09b8506c 100644 --- a/control-plane/internal/cli/root_test.go +++ b/control-plane/internal/cli/root_test.go @@ -65,8 +65,8 @@ func TestRootCommandHonorsConfigFlag(t *testing.T) { resetCLIStateForTest() configDir := t.TempDir() - configPath := filepath.Join(configDir, "brain.yaml") - require.NoError(t, os.WriteFile(configPath, []byte("brain:\n port: 7000\n"), 0o644)) + configPath := filepath.Join(configDir, "haxen.yaml") + require.NoError(t, os.WriteFile(configPath, []byte("haxen:\n port: 7000\n"), 0o644)) var received string cmd := NewRootCommand(func(cmd *cobra.Command, args []string) { diff --git a/control-plane/internal/cli/stop.go b/control-plane/internal/cli/stop.go index 0c6c4ed9..72ac6b46 100644 --- a/control-plane/internal/cli/stop.go +++ b/control-plane/internal/cli/stop.go @@ -12,22 +12,22 @@ import ( "github.com/spf13/cobra" "gopkg.in/yaml.v3" - "github.com/your-org/brain/control-plane/internal/packages" + "github.com/your-org/haxen/control-plane/internal/packages" ) // NewStopCommand creates the stop command func NewStopCommand() *cobra.Command { cmd := &cobra.Command{ Use: "stop ", - Short: "Stop a running Brain agent node", - Long: `Stop a running Brain agent node package. + Short: "Stop a running Haxen agent node", + Long: `Stop a running Haxen agent node package. The agent node process will be terminated gracefully and its status will be updated in the registry. Examples: - brain stop email-helper - brain stop data-analyzer`, + haxen stop email-helper + haxen stop data-analyzer`, Args: cobra.ExactArgs(1), Run: runStopCommand, } @@ -39,7 +39,7 @@ func runStopCommand(cmd *cobra.Command, args []string) { agentNodeName := args[0] stopper := &AgentNodeStopper{ - BrainHome: getBrainHomeDir(), + HaxenHome: getHaxenHomeDir(), } if err := stopper.StopAgentNode(agentNodeName); err != nil { @@ -50,7 +50,7 @@ func runStopCommand(cmd *cobra.Command, args []string) { // AgentNodeStopper handles stopping agent nodes type AgentNodeStopper struct { - BrainHome string + HaxenHome string } // StopAgentNode stops a running agent node @@ -103,7 +103,7 @@ func (as *AgentNodeStopper) StopAgentNode(agentNodeName string) error { req, err := http.NewRequest("POST", shutdownURL, bytes.NewReader(bodyBytes)) if err == nil { req.Header.Set("Content-Type", "application/json") - req.Header.Set("User-Agent", "Brain-CLI/1.0") + req.Header.Set("User-Agent", "Haxen-CLI/1.0") client := &http.Client{Timeout: 10 * time.Second} resp, err := client.Do(req) @@ -168,7 +168,7 @@ func (as *AgentNodeStopper) StopAgentNode(agentNodeName string) error { // loadRegistry loads the installation registry func (as *AgentNodeStopper) loadRegistry() (*packages.InstallationRegistry, error) { - registryPath := filepath.Join(as.BrainHome, "installed.yaml") + registryPath := filepath.Join(as.HaxenHome, "installed.yaml") registry := &packages.InstallationRegistry{ Installed: make(map[string]packages.InstalledPackage), @@ -185,7 +185,7 @@ func (as *AgentNodeStopper) loadRegistry() (*packages.InstallationRegistry, erro // saveRegistry saves the installation registry func (as *AgentNodeStopper) saveRegistry(registry *packages.InstallationRegistry) error { - registryPath := filepath.Join(as.BrainHome, "installed.yaml") + registryPath := filepath.Join(as.HaxenHome, "installed.yaml") data, err := yaml.Marshal(registry) if err != nil { diff --git a/control-plane/internal/cli/uninstall.go b/control-plane/internal/cli/uninstall.go index fccddb6d..78dc1900 100644 --- a/control-plane/internal/cli/uninstall.go +++ b/control-plane/internal/cli/uninstall.go @@ -5,7 +5,7 @@ import ( "os" "github.com/spf13/cobra" - "github.com/your-org/brain/control-plane/internal/packages" + "github.com/your-org/haxen/control-plane/internal/packages" ) var ( @@ -26,8 +26,8 @@ This command will: - Clean up any associated logs Examples: - brain uninstall my-agent - brain uninstall sentiment-analyzer --force`, + haxen uninstall my-agent + haxen uninstall sentiment-analyzer --force`, Args: cobra.ExactArgs(1), Run: runUninstallCommand, } @@ -42,7 +42,7 @@ func runUninstallCommand(cmd *cobra.Command, args []string) { // Create uninstaller uninstaller := &packages.PackageUninstaller{ - BrainHome: getBrainHomeDir(), + HaxenHome: getHaxenHomeDir(), Force: uninstallForce, } diff --git a/control-plane/internal/cli/utils.go b/control-plane/internal/cli/utils.go index 069c1891..ded5cddc 100644 --- a/control-plane/internal/cli/utils.go +++ b/control-plane/internal/cli/utils.go @@ -10,32 +10,32 @@ import ( "github.com/fatih/color" ) -// getBrainHomeDir returns the Brain home directory (~/.brain) and ensures it exists -func getBrainHomeDir() string { +// getHaxenHomeDir returns the Haxen home directory (~/.haxen) and ensures it exists +func getHaxenHomeDir() string { homeDir, err := os.UserHomeDir() if err != nil { PrintError(fmt.Sprintf("Failed to get user home directory: %v", err)) os.Exit(1) } - brainHome := filepath.Join(homeDir, ".brain") + haxenHome := filepath.Join(homeDir, ".haxen") - // Ensure .brain directory exists - if err := os.MkdirAll(brainHome, 0755); err != nil { - PrintError(fmt.Sprintf("Failed to create .brain directory: %v", err)) + // Ensure .haxen directory exists + if err := os.MkdirAll(haxenHome, 0755); err != nil { + PrintError(fmt.Sprintf("Failed to create .haxen directory: %v", err)) os.Exit(1) } // Ensure subdirectories exist subdirs := []string{"packages", "logs", "config"} for _, subdir := range subdirs { - if err := os.MkdirAll(filepath.Join(brainHome, subdir), 0755); err != nil { + if err := os.MkdirAll(filepath.Join(haxenHome, subdir), 0755); err != nil { PrintError(fmt.Sprintf("Failed to create %s directory: %v", subdir, err)) os.Exit(1) } } - return brainHome + return haxenHome } // Professional CLI status symbols diff --git a/control-plane/internal/cli/vc.go b/control-plane/internal/cli/vc.go index 5b52d897..38a58af6 100644 --- a/control-plane/internal/cli/vc.go +++ b/control-plane/internal/cli/vc.go @@ -12,7 +12,7 @@ import ( "time" "github.com/spf13/cobra" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" ) // NewVCCommand creates the vc command with subcommands @@ -20,7 +20,7 @@ func NewVCCommand() *cobra.Command { vcCmd := &cobra.Command{ Use: "vc", Short: "Verifiable Credential operations", - Long: `Commands for working with Brain Verifiable Credentials (VCs)`, + Long: `Commands for working with Haxen Verifiable Credentials (VCs)`, } vcCmd.AddCommand(NewVCVerifyCommand()) @@ -36,8 +36,8 @@ func NewVCVerifyCommand() *cobra.Command { verifyCmd := &cobra.Command{ Use: "verify ", - Short: "Verify a Brain Verifiable Credential", - Long: `Verify the cryptographic signature and integrity of a Brain Verifiable Credential. + Short: "Verify a Haxen Verifiable Credential", + Long: `Verify the cryptographic signature and integrity of a Haxen Verifiable Credential. This command supports offline verification with bundled DIDs and online verification with web resolution.`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { @@ -203,7 +203,7 @@ func verifyVC(vcFilePath string, options VerifyOptions) error { enhancedChain = convertLegacyChain(workflowChain) } else { step2.Success = false - step2.Error = "Invalid VC format: not a recognized Brain VC structure" + step2.Error = "Invalid VC format: not a recognized Haxen VC structure" result.VerificationSteps = append(result.VerificationSteps, step2) result.Valid = false result.FormatValid = false @@ -618,7 +618,7 @@ func outputPretty(result VCVerificationResult, verbose bool) error { status = "✅ VALID" } - fmt.Printf("Brain VC Verification: %s\n", status) + fmt.Printf("Haxen VC Verification: %s\n", status) fmt.Printf("Type: %s\n", result.Type) if result.WorkflowID != "" { diff --git a/control-plane/internal/cli/vc_verification_enhanced.go b/control-plane/internal/cli/vc_verification_enhanced.go index e8714002..1a59d497 100644 --- a/control-plane/internal/cli/vc_verification_enhanced.go +++ b/control-plane/internal/cli/vc_verification_enhanced.go @@ -7,7 +7,7 @@ import ( "fmt" "time" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" ) // EnhancedVCVerifier provides comprehensive VC verification with all integrity checks @@ -84,7 +84,7 @@ type SecurityAnalysis struct { // ComplianceChecks represents compliance and audit verification results type ComplianceChecks struct { W3CCompliance bool `json:"w3c_compliance"` - BrainStandardCompliance bool `json:"brain_standard_compliance"` + HaxenStandardCompliance bool `json:"haxen_standard_compliance"` AuditTrailIntegrity bool `json:"audit_trail_integrity"` DataIntegrityChecks bool `json:"data_integrity_checks"` Issues []VerificationIssue `json:"issues"` @@ -198,7 +198,7 @@ func (v *EnhancedVCVerifier) verifyExecutionVCComprehensive(execVC types.Executi return result } - // CRITICAL CHECK 7: Status consistency (with Brain system status mapping) + // CRITICAL CHECK 7: Status consistency (with Haxen system status mapping) if !v.isStatusConsistent(execVC.Status, vcDoc.CredentialSubject.Execution.Status) { result.Valid = false result.Error = fmt.Sprintf("Status mismatch: metadata=%s, vc_document=%s", execVC.Status, vcDoc.CredentialSubject.Execution.Status) @@ -388,7 +388,7 @@ func (v *EnhancedVCVerifier) performSecurityAnalysis(chain EnhancedVCChain) Secu func (v *EnhancedVCVerifier) performComplianceChecks(chain EnhancedVCChain) ComplianceChecks { result := ComplianceChecks{ W3CCompliance: true, - BrainStandardCompliance: true, + HaxenStandardCompliance: true, AuditTrailIntegrity: true, DataIntegrityChecks: true, Issues: []VerificationIssue{}, @@ -581,7 +581,7 @@ func (v *EnhancedVCVerifier) calculateOverallScore(result *ComprehensiveVerifica return score } -// isStatusConsistent checks if status values are consistent, accounting for Brain system status mapping +// isStatusConsistent checks if status values are consistent, accounting for Haxen system status mapping func (v *EnhancedVCVerifier) isStatusConsistent(metadataStatus, vcDocStatus string) bool { return types.NormalizeExecutionStatus(metadataStatus) == types.NormalizeExecutionStatus(vcDocStatus) } diff --git a/control-plane/internal/config/config.go b/control-plane/internal/config/config.go index 827d824d..3da5081d 100644 --- a/control-plane/internal/config/config.go +++ b/control-plane/internal/config/config.go @@ -7,12 +7,12 @@ import ( "path/filepath" // Added for filepath.Join "time" - "github.com/your-org/brain/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/internal/storage" ) -// Config holds the entire configuration for the Brain server. +// Config holds the entire configuration for the Haxen server. type Config struct { - Brain BrainConfig `yaml:"brain" mapstructure:"brain"` + Haxen HaxenConfig `yaml:"haxen" mapstructure:"haxen"` Agents AgentsConfig `yaml:"agents" mapstructure:"agents"` Features FeatureConfig `yaml:"features" mapstructure:"features"` Storage StorageConfig `yaml:"storage" mapstructure:"storage"` // Added storage config @@ -31,8 +31,8 @@ type UIConfig struct { BackendURL string `yaml:"backend_url" mapstructure:"backend_url"` // URL of the backend if UI is separate } -// BrainConfig holds the core Brain server configuration. -type BrainConfig struct { +// HaxenConfig holds the core Haxen server configuration. +type HaxenConfig struct { Port int `yaml:"port"` DatabaseURL string `yaml:"database_url"` RedisURL string `yaml:"redis_url"` @@ -166,21 +166,21 @@ type CORSConfig struct { // with the implementation in the storage package. type StorageConfig = storage.StorageConfig -// DataDirectoriesConfig holds configuration for Brain data directory paths +// DataDirectoriesConfig holds configuration for Haxen data directory paths type DataDirectoriesConfig struct { - BrainHome string `yaml:"brain_home" mapstructure:"brain_home"` // Can be overridden by BRAIN_HOME env var - DatabaseDir string `yaml:"database_dir" mapstructure:"database_dir"` // Relative to brain_home - KeysDir string `yaml:"keys_dir" mapstructure:"keys_dir"` // Relative to brain_home - DIDRegistriesDir string `yaml:"did_registries_dir" mapstructure:"did_registries_dir"` // Relative to brain_home - VCsDir string `yaml:"vcs_dir" mapstructure:"vcs_dir"` // Relative to brain_home - AgentsDir string `yaml:"agents_dir" mapstructure:"agents_dir"` // Relative to brain_home - LogsDir string `yaml:"logs_dir" mapstructure:"logs_dir"` // Relative to brain_home - ConfigDir string `yaml:"config_dir" mapstructure:"config_dir"` // Relative to brain_home - TempDir string `yaml:"temp_dir" mapstructure:"temp_dir"` // Relative to brain_home + HaxenHome string `yaml:"haxen_home" mapstructure:"haxen_home"` // Can be overridden by HAXEN_HOME env var + DatabaseDir string `yaml:"database_dir" mapstructure:"database_dir"` // Relative to haxen_home + KeysDir string `yaml:"keys_dir" mapstructure:"keys_dir"` // Relative to haxen_home + DIDRegistriesDir string `yaml:"did_registries_dir" mapstructure:"did_registries_dir"` // Relative to haxen_home + VCsDir string `yaml:"vcs_dir" mapstructure:"vcs_dir"` // Relative to haxen_home + AgentsDir string `yaml:"agents_dir" mapstructure:"agents_dir"` // Relative to haxen_home + LogsDir string `yaml:"logs_dir" mapstructure:"logs_dir"` // Relative to haxen_home + ConfigDir string `yaml:"config_dir" mapstructure:"config_dir"` // Relative to haxen_home + TempDir string `yaml:"temp_dir" mapstructure:"temp_dir"` // Relative to haxen_home } -// DefaultConfigPath is the default path for the brain configuration file. -const DefaultConfigPath = "brain.yaml" // Or "./brain.yaml", "config/brain.yaml" depending on convention +// DefaultConfigPath is the default path for the haxen configuration file. +const DefaultConfigPath = "haxen.yaml" // Or "./haxen.yaml", "config/haxen.yaml" depending on convention // LoadConfig reads the configuration from the given path or default paths. func LoadConfig(configPath string) (*Config, error) { @@ -194,7 +194,7 @@ func LoadConfig(configPath string) (*Config, error) { // This part might need more sophisticated logic depending on project structure // For now, let's assume configPath is either absolute or relative to CWD. // If not found, try a common "config/" subdirectory - altPath := filepath.Join("config", "brain.yaml") + altPath := filepath.Join("config", "haxen.yaml") if _, err2 := os.Stat(altPath); err2 == nil { configPath = altPath } else { diff --git a/control-plane/internal/config/package_config.go b/control-plane/internal/config/package_config.go index 71f82482..cc275d82 100644 --- a/control-plane/internal/config/package_config.go +++ b/control-plane/internal/config/package_config.go @@ -11,7 +11,7 @@ import ( "gopkg.in/yaml.v3" ) -// ConfigurationField represents a single configuration field in brain-package.yaml +// ConfigurationField represents a single configuration field in haxen-package.yaml type ConfigurationField struct { Name string `yaml:"name" json:"name"` Description string `yaml:"description" json:"description"` @@ -23,14 +23,14 @@ type ConfigurationField struct { Max *int `yaml:"max" json:"max,omitempty"` // for integer/float } -// ConfigurationSchema represents the configuration schema from brain-package.yaml +// ConfigurationSchema represents the configuration schema from haxen-package.yaml type ConfigurationSchema struct { Required []ConfigurationField `yaml:"required" json:"required"` Optional []ConfigurationField `yaml:"optional" json:"optional"` } -// BrainPackageConfig represents the structure of brain-package.yaml -type BrainPackageConfig struct { +// HaxenPackageConfig represents the structure of haxen-package.yaml +type HaxenPackageConfig struct { Name string `yaml:"name"` Version string `yaml:"version"` Description string `yaml:"description"` @@ -78,22 +78,22 @@ type MetadataConfig struct { Platform string `yaml:"platform"` } -// LoadBrainPackageConfig loads and parses a brain-package.yaml file -func LoadBrainPackageConfig(packagePath string) (*BrainPackageConfig, error) { - configPath := filepath.Join(packagePath, "brain-package.yaml") +// LoadHaxenPackageConfig loads and parses a haxen-package.yaml file +func LoadHaxenPackageConfig(packagePath string) (*HaxenPackageConfig, error) { + configPath := filepath.Join(packagePath, "haxen-package.yaml") if _, err := os.Stat(configPath); os.IsNotExist(err) { - return nil, fmt.Errorf("brain-package.yaml not found at %s", configPath) + return nil, fmt.Errorf("haxen-package.yaml not found at %s", configPath) } data, err := os.ReadFile(configPath) if err != nil { - return nil, fmt.Errorf("failed to read brain-package.yaml: %w", err) + return nil, fmt.Errorf("failed to read haxen-package.yaml: %w", err) } - var config BrainPackageConfig + var config HaxenPackageConfig if err := yaml.Unmarshal(data, &config); err != nil { - return nil, fmt.Errorf("failed to parse brain-package.yaml: %w", err) + return nil, fmt.Errorf("failed to parse haxen-package.yaml: %w", err) } // Validate the configuration schema diff --git a/control-plane/internal/config/package_config_test.go b/control-plane/internal/config/package_config_test.go index 97d6e217..e427369b 100644 --- a/control-plane/internal/config/package_config_test.go +++ b/control-plane/internal/config/package_config_test.go @@ -6,11 +6,11 @@ import ( "testing" ) -func TestLoadBrainPackageConfig(t *testing.T) { +func TestLoadHaxenPackageConfig(t *testing.T) { // Create a temporary test directory tempDir := t.TempDir() - // Create a test brain-package.yaml + // Create a test haxen-package.yaml testConfig := ` name: "test-agent" version: "1.0.0" @@ -24,7 +24,7 @@ agent_node: default_port: 8001 dependencies: - python: ["brain-sdk>=1.0.0"] + python: ["haxen-sdk>=1.0.0"] capabilities: reasoners: @@ -73,17 +73,17 @@ metadata: created_at: "2025-06-20" sdk_version: "1.0.0" language: "python" - platform: "brain-agent-node" + platform: "haxen-agent-node" ` - configPath := filepath.Join(tempDir, "brain-package.yaml") + configPath := filepath.Join(tempDir, "haxen-package.yaml") err := os.WriteFile(configPath, []byte(testConfig), 0644) if err != nil { t.Fatalf("Failed to write test config: %v", err) } // Test loading the configuration - config, err := LoadBrainPackageConfig(tempDir) + config, err := LoadHaxenPackageConfig(tempDir) if err != nil { t.Fatalf("Failed to load config: %v", err) } diff --git a/control-plane/internal/core/domain/models.go b/control-plane/internal/core/domain/models.go index 3bee31e9..195423d3 100644 --- a/control-plane/internal/core/domain/models.go +++ b/control-plane/internal/core/domain/models.go @@ -1,4 +1,4 @@ -// brain/internal/core/domain/models.go +// haxen/internal/core/domain/models.go package domain import "time" @@ -56,8 +56,8 @@ type InstalledPackage struct { InstalledAt time.Time `json:"installed_at"` } -// BrainConfig represents the Brain configuration -type BrainConfig struct { +// HaxenConfig represents the Haxen configuration +type HaxenConfig struct { HomeDir string `json:"home_dir"` Environment map[string]string `json:"environment"` MCP MCPConfig `json:"mcp"` diff --git a/control-plane/internal/core/interfaces/services.go b/control-plane/internal/core/interfaces/services.go index 27843c00..c1fc82d7 100644 --- a/control-plane/internal/core/interfaces/services.go +++ b/control-plane/internal/core/interfaces/services.go @@ -1,7 +1,7 @@ package interfaces import ( - "github.com/your-org/brain/control-plane/internal/core/domain" + "github.com/your-org/haxen/control-plane/internal/core/domain" ) // PackageService defines the contract for package management operations. diff --git a/control-plane/internal/core/interfaces/storage.go b/control-plane/internal/core/interfaces/storage.go index 4b1e61e6..b70fc251 100644 --- a/control-plane/internal/core/interfaces/storage.go +++ b/control-plane/internal/core/interfaces/storage.go @@ -1,7 +1,7 @@ -// brain/internal/core/interfaces/storage.go +// haxen/internal/core/interfaces/storage.go package interfaces -import "github.com/your-org/brain/control-plane/internal/core/domain" +import "github.com/your-org/haxen/control-plane/internal/core/domain" type FileSystemAdapter interface { ReadFile(path string) ([]byte, error) @@ -19,6 +19,6 @@ type RegistryStorage interface { } type ConfigStorage interface { - LoadBrainConfig(path string) (*domain.BrainConfig, error) - SaveBrainConfig(path string, config *domain.BrainConfig) error + LoadHaxenConfig(path string) (*domain.HaxenConfig, error) + SaveHaxenConfig(path string, config *domain.HaxenConfig) error } diff --git a/control-plane/internal/core/services/agent_service.go b/control-plane/internal/core/services/agent_service.go index 1377bebf..0f520433 100644 --- a/control-plane/internal/core/services/agent_service.go +++ b/control-plane/internal/core/services/agent_service.go @@ -1,4 +1,4 @@ -// brain/internal/core/services/agent_service.go +// haxen/internal/core/services/agent_service.go package services import ( @@ -14,9 +14,9 @@ import ( "syscall" "time" - "github.com/your-org/brain/control-plane/internal/core/interfaces" - "github.com/your-org/brain/control-plane/internal/core/domain" - "github.com/your-org/brain/control-plane/internal/packages" + "github.com/your-org/haxen/control-plane/internal/core/interfaces" + "github.com/your-org/haxen/control-plane/internal/core/domain" + "github.com/your-org/haxen/control-plane/internal/packages" "gopkg.in/yaml.v3" ) @@ -26,7 +26,7 @@ type DefaultAgentService struct { portManager interfaces.PortManager registryStorage interfaces.RegistryStorage agentClient interfaces.AgentClient - brainHome string + haxenHome string } // NewAgentService creates a new agent service instance @@ -35,14 +35,14 @@ func NewAgentService( portManager interfaces.PortManager, registryStorage interfaces.RegistryStorage, agentClient interfaces.AgentClient, - brainHome string, + haxenHome string, ) interfaces.AgentService { return &DefaultAgentService{ processManager: processManager, portManager: portManager, registryStorage: registryStorage, agentClient: agentClient, - brainHome: brainHome, + haxenHome: haxenHome, } } @@ -107,7 +107,7 @@ func (as *DefaultAgentService) RunAgent(name string, options domain.RunOptions) return nil, fmt.Errorf("agent node failed to start: %w", err) } - fmt.Printf("🧠 Agent node registered with Brain Server\n") + fmt.Printf("🧠 Agent node registered with Haxen Server\n") // 6. Update registry with runtime info if err := as.updateRuntimeInfo(name, port, pid); err != nil { @@ -120,8 +120,8 @@ func (as *DefaultAgentService) RunAgent(name string, options domain.RunOptions) } fmt.Printf("\n💡 Agent node running in background (PID: %d)\n", pid) - fmt.Printf("💡 View logs: brain logs %s\n", name) - fmt.Printf("💡 Stop agent node: brain stop %s\n", name) + fmt.Printf("💡 View logs: haxen logs %s\n", name) + fmt.Printf("💡 Stop agent node: haxen stop %s\n", name) // Convert to domain model and return runningAgent := as.convertToRunningAgent(agentNode) @@ -387,7 +387,7 @@ func (as *DefaultAgentService) ListRunningAgents() ([]domain.RunningAgent, error // loadRegistryDirect loads the registry using direct file system access // TODO: Eventually replace with registryStorage interface usage func (as *DefaultAgentService) loadRegistryDirect() (*packages.InstallationRegistry, error) { - registryPath := filepath.Join(as.brainHome, "installed.yaml") + registryPath := filepath.Join(as.haxenHome, "installed.yaml") registry := &packages.InstallationRegistry{ Installed: make(map[string]packages.InstalledPackage), @@ -405,7 +405,7 @@ func (as *DefaultAgentService) loadRegistryDirect() (*packages.InstallationRegis // saveRegistryDirect saves the registry using direct file system access // TODO: Eventually replace with registryStorage interface usage func (as *DefaultAgentService) saveRegistryDirect(registry *packages.InstallationRegistry) error { - registryPath := filepath.Join(as.brainHome, "installed.yaml") + registryPath := filepath.Join(as.haxenHome, "installed.yaml") data, err := yaml.Marshal(registry) if err != nil { @@ -446,7 +446,7 @@ func (as *DefaultAgentService) buildProcessConfig(agentNode packages.InstalledPa // Prepare environment variables env := os.Environ() env = append(env, fmt.Sprintf("PORT=%d", port)) - env = append(env, "BRAIN_SERVER_URL=http://localhost:8080") + env = append(env, "HAXEN_SERVER_URL=http://localhost:8080") // Load environment variables from package .env file if envVars, err := as.loadPackageEnvFile(agentNode.Path); err == nil { @@ -544,7 +544,7 @@ func (as *DefaultAgentService) waitForAgentNode(port int, timeout time.Duration) // updateRuntimeInfo updates the registry with runtime information func (as *DefaultAgentService) updateRuntimeInfo(agentNodeName string, port, pid int) error { - registryPath := filepath.Join(as.brainHome, "installed.yaml") + registryPath := filepath.Join(as.haxenHome, "installed.yaml") // Load registry registry := &packages.InstallationRegistry{} diff --git a/control-plane/internal/core/services/dev_service.go b/control-plane/internal/core/services/dev_service.go index 0cc356b5..97f07a25 100644 --- a/control-plane/internal/core/services/dev_service.go +++ b/control-plane/internal/core/services/dev_service.go @@ -15,8 +15,8 @@ import ( "syscall" "time" - "github.com/your-org/brain/control-plane/internal/core/domain" - "github.com/your-org/brain/control-plane/internal/core/interfaces" + "github.com/your-org/haxen/control-plane/internal/core/domain" + "github.com/your-org/haxen/control-plane/internal/core/interfaces" ) type DefaultDevService struct { @@ -44,10 +44,10 @@ func (ds *DefaultDevService) RunInDevMode(path string, options domain.DevOptions return fmt.Errorf("failed to resolve path: %w", err) } - // Check if brain.yaml exists - brainYamlPath := filepath.Join(absPath, "brain.yaml") - if !ds.fileSystem.Exists(brainYamlPath) { - return fmt.Errorf("no brain.yaml found in %s", absPath) + // Check if haxen.yaml exists + haxenYamlPath := filepath.Join(absPath, "haxen.yaml") + if !ds.fileSystem.Exists(haxenYamlPath) { + return fmt.Errorf("no haxen.yaml found in %s", absPath) } return ds.runDev(absPath, options) @@ -180,8 +180,8 @@ func (ds *DefaultDevService) startDevProcess(packagePath string, port int, optio if port > 0 { env = append(env, fmt.Sprintf("PORT=%d", port)) } - env = append(env, "BRAIN_SERVER_URL=http://localhost:8080") - env = append(env, "BRAIN_DEV_MODE=true") + env = append(env, "HAXEN_SERVER_URL=http://localhost:8080") + env = append(env, "HAXEN_DEV_MODE=true") // Load environment variables from package .env file if envVars, err := ds.loadDevEnvFile(packagePath); err == nil { diff --git a/control-plane/internal/core/services/package_service.go b/control-plane/internal/core/services/package_service.go index aadedd54..af12015a 100644 --- a/control-plane/internal/core/services/package_service.go +++ b/control-plane/internal/core/services/package_service.go @@ -1,4 +1,4 @@ -// brain/internal/core/services/package_service.go +// haxen/internal/core/services/package_service.go package services import ( @@ -10,9 +10,9 @@ import ( "sync" "time" - "github.com/your-org/brain/control-plane/internal/core/interfaces" - "github.com/your-org/brain/control-plane/internal/core/domain" - "github.com/your-org/brain/control-plane/internal/packages" + "github.com/your-org/haxen/control-plane/internal/core/interfaces" + "github.com/your-org/haxen/control-plane/internal/core/domain" + "github.com/your-org/haxen/control-plane/internal/packages" "github.com/fatih/color" "gopkg.in/yaml.v3" ) @@ -21,19 +21,19 @@ import ( type DefaultPackageService struct { registryStorage interfaces.RegistryStorage fileSystem interfaces.FileSystemAdapter - brainHome string + haxenHome string } // NewPackageService creates a new package service instance func NewPackageService( registryStorage interfaces.RegistryStorage, fileSystem interfaces.FileSystemAdapter, - brainHome string, + haxenHome string, ) interfaces.PackageService { return &DefaultPackageService{ registryStorage: registryStorage, fileSystem: fileSystem, - brainHome: brainHome, + haxenHome: haxenHome, } } @@ -42,7 +42,7 @@ func (ps *DefaultPackageService) InstallPackage(source string, options domain.In // Check if it's a Git URL (GitHub, GitLab, Bitbucket, etc.) if packages.IsGitURL(source) { installer := &packages.GitInstaller{ - BrainHome: ps.brainHome, + HaxenHome: ps.haxenHome, Verbose: options.Verbose, } return installer.InstallFromGit(source, options.Force) @@ -77,7 +77,7 @@ func (ps *DefaultPackageService) installLocalPackage(sourcePath string, force bo } // 3. Copy package to global location - destPath := filepath.Join(ps.brainHome, "packages", metadata.Name) + destPath := filepath.Join(ps.haxenHome, "packages", metadata.Name) spinner = ps.newSpinner("Setting up environment") spinner.Start() if err := ps.copyPackage(sourcePath, destPath); err != nil { @@ -106,7 +106,7 @@ func (ps *DefaultPackageService) installLocalPackage(sourcePath string, force bo // 6. Check for required environment variables and provide guidance ps.checkEnvironmentVariables(metadata) - fmt.Printf("\n%s %s\n", ps.blue("→"), ps.bold(fmt.Sprintf("Run: brain run %s", metadata.Name))) + fmt.Printf("\n%s %s\n", ps.blue("→"), ps.bold(fmt.Sprintf("Run: haxen run %s", metadata.Name))) return nil } @@ -188,7 +188,7 @@ func (ps *DefaultPackageService) stopAgentNode(agentNode *packages.InstalledPack // saveRegistry saves the installation registry func (ps *DefaultPackageService) saveRegistry(registry *packages.InstallationRegistry) error { - registryPath := filepath.Join(ps.brainHome, "installed.yaml") + registryPath := filepath.Join(ps.haxenHome, "installed.yaml") data, err := yaml.Marshal(registry) if err != nil { @@ -239,7 +239,7 @@ func (ps *DefaultPackageService) GetPackageInfo(name string) (*domain.InstalledP // loadRegistryDirect loads the registry using direct file system access // TODO: Eventually replace with registryStorage interface usage func (ps *DefaultPackageService) loadRegistryDirect() (*packages.InstallationRegistry, error) { - registryPath := filepath.Join(ps.brainHome, "installed.yaml") + registryPath := filepath.Join(ps.haxenHome, "installed.yaml") registry := &packages.InstallationRegistry{ Installed: make(map[string]packages.InstalledPackage), @@ -373,10 +373,10 @@ func (s *Spinner) Error(message string) { // validatePackage checks if the package has required files func (ps *DefaultPackageService) validatePackage(sourcePath string) error { - // Check if brain-package.yaml exists - packageYamlPath := filepath.Join(sourcePath, "brain-package.yaml") + // Check if haxen-package.yaml exists + packageYamlPath := filepath.Join(sourcePath, "haxen-package.yaml") if _, err := os.Stat(packageYamlPath); os.IsNotExist(err) { - return fmt.Errorf("brain-package.yaml not found in %s", sourcePath) + return fmt.Errorf("haxen-package.yaml not found in %s", sourcePath) } // Check if main.py exists @@ -388,26 +388,26 @@ func (ps *DefaultPackageService) validatePackage(sourcePath string) error { return nil } -// parsePackageMetadata parses the brain-package.yaml file +// parsePackageMetadata parses the haxen-package.yaml file func (ps *DefaultPackageService) parsePackageMetadata(sourcePath string) (*packages.PackageMetadata, error) { - packageYamlPath := filepath.Join(sourcePath, "brain-package.yaml") + packageYamlPath := filepath.Join(sourcePath, "haxen-package.yaml") data, err := os.ReadFile(packageYamlPath) if err != nil { - return nil, fmt.Errorf("failed to read brain-package.yaml: %w", err) + return nil, fmt.Errorf("failed to read haxen-package.yaml: %w", err) } var metadata packages.PackageMetadata if err := yaml.Unmarshal(data, &metadata); err != nil { - return nil, fmt.Errorf("failed to parse brain-package.yaml: %w", err) + return nil, fmt.Errorf("failed to parse haxen-package.yaml: %w", err) } // Validate required fields if metadata.Name == "" { - return nil, fmt.Errorf("package name is required in brain-package.yaml") + return nil, fmt.Errorf("package name is required in haxen-package.yaml") } if metadata.Version == "" { - return nil, fmt.Errorf("package version is required in brain-package.yaml") + return nil, fmt.Errorf("package version is required in haxen-package.yaml") } if metadata.Main == "" { metadata.Main = "main.py" // Default @@ -418,7 +418,7 @@ func (ps *DefaultPackageService) parsePackageMetadata(sourcePath string) (*packa // isPackageInstalled checks if a package is already installed func (ps *DefaultPackageService) isPackageInstalled(packageName string) bool { - registryPath := filepath.Join(ps.brainHome, "installed.yaml") + registryPath := filepath.Join(ps.haxenHome, "installed.yaml") registry := &packages.InstallationRegistry{ Installed: make(map[string]packages.InstalledPackage), } @@ -524,7 +524,7 @@ func (ps *DefaultPackageService) installDependencies(packagePath string, metadat } } - // Install dependencies from brain-package.yaml + // Install dependencies from haxen-package.yaml if len(metadata.Dependencies.Python) > 0 { for _, dep := range metadata.Dependencies.Python { cmd = exec.Command(pipPath, "install", dep) @@ -553,7 +553,7 @@ func (ps *DefaultPackageService) hasRequirementsFile(packagePath string) bool { // updateRegistry updates the installation registry with the new package func (ps *DefaultPackageService) updateRegistry(metadata *packages.PackageMetadata, sourcePath, destPath string) error { - registryPath := filepath.Join(ps.brainHome, "installed.yaml") + registryPath := filepath.Join(ps.haxenHome, "installed.yaml") // Load existing registry or create new one registry := &packages.InstallationRegistry{ @@ -578,7 +578,7 @@ func (ps *DefaultPackageService) updateRegistry(metadata *packages.PackageMetada Port: nil, PID: nil, StartedAt: nil, - LogFile: filepath.Join(ps.brainHome, "logs", metadata.Name+".log"), + LogFile: filepath.Join(ps.haxenHome, "logs", metadata.Name+".log"), }, } @@ -617,7 +617,7 @@ func (ps *DefaultPackageService) checkEnvironmentVariables(metadata *packages.Pa if len(missingRequired) > 0 { fmt.Printf("\n%s %s\n", ps.yellow("⚠"), ps.bold("Missing required environment variables:")) for _, envVar := range missingRequired { - fmt.Printf(" %s\n", ps.cyan(fmt.Sprintf("brain config %s --set %s=your-value-here", metadata.Name, envVar.Name))) + fmt.Printf(" %s\n", ps.cyan(fmt.Sprintf("haxen config %s --set %s=your-value-here", metadata.Name, envVar.Name))) } } diff --git a/control-plane/internal/events/execution_events.go b/control-plane/internal/events/execution_events.go index 98c6806d..8f11a104 100644 --- a/control-plane/internal/events/execution_events.go +++ b/control-plane/internal/events/execution_events.go @@ -5,8 +5,8 @@ import ( "sync" "time" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/pkg/types" ) // ExecutionEventType represents the type of execution event diff --git a/control-plane/internal/events/node_events.go b/control-plane/internal/events/node_events.go index cd18c046..07634026 100644 --- a/control-plane/internal/events/node_events.go +++ b/control-plane/internal/events/node_events.go @@ -6,7 +6,7 @@ import ( "sync" "time" - "github.com/your-org/brain/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/logger" ) // NodeEventType represents the type of node event diff --git a/control-plane/internal/handlers/did_handlers.go b/control-plane/internal/handlers/did_handlers.go index 3a4e5dc6..efc0e4c4 100644 --- a/control-plane/internal/handlers/did_handlers.go +++ b/control-plane/internal/handlers/did_handlers.go @@ -7,8 +7,8 @@ import ( "github.com/gin-gonic/gin" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/pkg/types" ) // DIDService defines the DID operations required by handlers. @@ -417,10 +417,10 @@ func (h *DIDHandlers) GetDIDDocument(c *gin.Context) { }, "service": []map[string]interface{}{ { - "id": did + "#brain-service", - "type": "BrainAgentService", - "serviceEndpoint": "https://brain.example.com/api/v1", - "description": "Brain Agent Platform Service", + "id": did + "#haxen-service", + "type": "HaxenAgentService", + "serviceEndpoint": "https://haxen.example.com/api/v1", + "description": "Haxen Agent Platform Service", }, }, } diff --git a/control-plane/internal/handlers/did_handlers_test.go b/control-plane/internal/handlers/did_handlers_test.go index 1b0baba1..8bdf59f5 100644 --- a/control-plane/internal/handlers/did_handlers_test.go +++ b/control-plane/internal/handlers/did_handlers_test.go @@ -9,7 +9,7 @@ import ( "testing" "time" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" diff --git a/control-plane/internal/handlers/execute.go b/control-plane/internal/handlers/execute.go index b40c3cf7..339a394e 100644 --- a/control-plane/internal/handlers/execute.go +++ b/control-plane/internal/handlers/execute.go @@ -16,10 +16,10 @@ import ( "sync" "time" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/internal/services" - "github.com/your-org/brain/control-plane/internal/utils" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/services" + "github.com/your-org/haxen/control-plane/internal/utils" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" ) @@ -883,12 +883,12 @@ func (p *asyncWorkerPool) submit(job asyncExecutionJob) bool { func getAsyncWorkerPool() *asyncWorkerPool { asyncPoolOnce.Do(func() { - workerCount := resolveIntFromEnv("BRAIN_EXEC_ASYNC_WORKERS", runtime.NumCPU()) + workerCount := resolveIntFromEnv("HAXEN_EXEC_ASYNC_WORKERS", runtime.NumCPU()) if workerCount <= 0 { workerCount = runtime.NumCPU() } - queueCapacity := resolveIntFromEnv("BRAIN_EXEC_ASYNC_QUEUE_CAPACITY", 1024) + queueCapacity := resolveIntFromEnv("HAXEN_EXEC_ASYNC_QUEUE_CAPACITY", 1024) if queueCapacity <= 0 { queueCapacity = 1024 } @@ -916,7 +916,7 @@ func resolveIntFromEnv(key string, fallback int) int { func ensureCompletionWorker() { completionOnce.Do(func() { - size := resolveIntFromEnv("BRAIN_EXEC_COMPLETION_QUEUE", 2048) + size := resolveIntFromEnv("HAXEN_EXEC_COMPLETION_QUEUE", 2048) if size <= 0 { size = 2048 } diff --git a/control-plane/internal/handlers/execute_handler_test.go b/control-plane/internal/handlers/execute_handler_test.go index 58bf1e05..7906d544 100644 --- a/control-plane/internal/handlers/execute_handler_test.go +++ b/control-plane/internal/handlers/execute_handler_test.go @@ -11,8 +11,8 @@ import ( "testing" "time" - "github.com/your-org/brain/control-plane/internal/services" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/services" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" diff --git a/control-plane/internal/handlers/execute_test.go b/control-plane/internal/handlers/execute_test.go index b26f7c96..c9ddec08 100644 --- a/control-plane/internal/handlers/execute_test.go +++ b/control-plane/internal/handlers/execute_test.go @@ -4,7 +4,7 @@ package handlers import ( - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" "bytes" "context" "encoding/json" @@ -224,16 +224,16 @@ func (m *MockStorageProvider) GetDID(ctx context.Context, did string) (*types.DI func (m *MockStorageProvider) ListDIDs(ctx context.Context) ([]*types.DIDRegistryEntry, error) { return nil, nil } -func (m *MockStorageProvider) StoreBrainServerDID(ctx context.Context, brainServerID, rootDID string, masterSeed []byte, createdAt, lastKeyRotation time.Time) error { +func (m *MockStorageProvider) StoreHaxenServerDID(ctx context.Context, haxenServerID, rootDID string, masterSeed []byte, createdAt, lastKeyRotation time.Time) error { return nil } -func (m *MockStorageProvider) GetBrainServerDID(ctx context.Context, brainServerID string) (*types.BrainServerDIDInfo, error) { +func (m *MockStorageProvider) GetHaxenServerDID(ctx context.Context, haxenServerID string) (*types.HaxenServerDIDInfo, error) { return nil, nil } -func (m *MockStorageProvider) ListBrainServerDIDs(ctx context.Context) ([]*types.BrainServerDIDInfo, error) { +func (m *MockStorageProvider) ListHaxenServerDIDs(ctx context.Context) ([]*types.HaxenServerDIDInfo, error) { return nil, nil } -func (m *MockStorageProvider) StoreAgentDID(ctx context.Context, agentID, agentDID, brainServerDID, publicKeyJWK string, derivationIndex int) error { +func (m *MockStorageProvider) StoreAgentDID(ctx context.Context, agentID, agentDID, haxenServerDID, publicKeyJWK string, derivationIndex int) error { return nil } func (m *MockStorageProvider) GetAgentDID(ctx context.Context, agentID string) (*types.AgentDIDInfo, error) { @@ -251,7 +251,7 @@ func (m *MockStorageProvider) GetComponentDID(ctx context.Context, componentID s func (m *MockStorageProvider) ListComponentDIDs(ctx context.Context, agentDID string) ([]*types.ComponentDIDInfo, error) { return nil, nil } -func (m *MockStorageProvider) StoreAgentDIDWithComponents(ctx context.Context, agentID, agentDID, brainServerDID, publicKeyJWK string, derivationIndex int, components []interface{}) error { +func (m *MockStorageProvider) StoreAgentDIDWithComponents(ctx context.Context, agentID, agentDID, haxenServerDID, publicKeyJWK string, derivationIndex int, components []interface{}) error { return nil } func (m *MockStorageProvider) StoreExecutionVC(ctx context.Context, vcID, executionID, workflowID, sessionID, issuerDID, targetDID, callerDID, inputHash, outputHash, status string, vcDocument []byte, signature string, storageURI string, documentSizeBytes int64) error { diff --git a/control-plane/internal/handlers/execution_cleanup.go b/control-plane/internal/handlers/execution_cleanup.go index fa8b7801..3b079127 100644 --- a/control-plane/internal/handlers/execution_cleanup.go +++ b/control-plane/internal/handlers/execution_cleanup.go @@ -1,9 +1,9 @@ package handlers import ( - "github.com/your-org/brain/control-plane/internal/config" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/internal/config" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/storage" "context" "sync" "time" diff --git a/control-plane/internal/handlers/execution_notes.go b/control-plane/internal/handlers/execution_notes.go index 33d8c2ff..823e28bf 100644 --- a/control-plane/internal/handlers/execution_notes.go +++ b/control-plane/internal/handlers/execution_notes.go @@ -7,8 +7,8 @@ import ( "strings" "time" - "github.com/your-org/brain/control-plane/internal/events" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/events" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" ) diff --git a/control-plane/internal/handlers/execution_notes_test.go b/control-plane/internal/handlers/execution_notes_test.go index 851dc8ed..859e4d7c 100644 --- a/control-plane/internal/handlers/execution_notes_test.go +++ b/control-plane/internal/handlers/execution_notes_test.go @@ -9,7 +9,7 @@ import ( "testing" "time" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" diff --git a/control-plane/internal/handlers/memory.go b/control-plane/internal/handlers/memory.go index 6da060a0..dde2b8d6 100644 --- a/control-plane/internal/handlers/memory.go +++ b/control-plane/internal/handlers/memory.go @@ -6,8 +6,8 @@ import ( "net/http" "time" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" ) diff --git a/control-plane/internal/handlers/memory_events.go b/control-plane/internal/handlers/memory_events.go index 30ac66d6..6d25ed6e 100644 --- a/control-plane/internal/handlers/memory_events.go +++ b/control-plane/internal/handlers/memory_events.go @@ -1,8 +1,8 @@ package handlers import ( - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "encoding/json" "net/http" "path/filepath" diff --git a/control-plane/internal/handlers/memory_handler_test.go b/control-plane/internal/handlers/memory_handler_test.go index a0b09477..30a69ea2 100644 --- a/control-plane/internal/handlers/memory_handler_test.go +++ b/control-plane/internal/handlers/memory_handler_test.go @@ -10,7 +10,7 @@ import ( "sync" "testing" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" diff --git a/control-plane/internal/handlers/nodes.go b/control-plane/internal/handlers/nodes.go index b28f247e..0b1c70bb 100644 --- a/control-plane/internal/handlers/nodes.go +++ b/control-plane/internal/handlers/nodes.go @@ -12,10 +12,10 @@ import ( "sync" "time" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/internal/services" // Import services package - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/services" // Import services package + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" diff --git a/control-plane/internal/handlers/nodes_rest.go b/control-plane/internal/handlers/nodes_rest.go index e7cc588f..5905e14c 100644 --- a/control-plane/internal/handlers/nodes_rest.go +++ b/control-plane/internal/handlers/nodes_rest.go @@ -6,10 +6,10 @@ import ( "strings" "time" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/internal/services" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/services" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" ) diff --git a/control-plane/internal/handlers/reasoners.go b/control-plane/internal/handlers/reasoners.go index 7133d29c..a53296ac 100644 --- a/control-plane/internal/handlers/reasoners.go +++ b/control-plane/internal/handlers/reasoners.go @@ -9,10 +9,10 @@ import ( "strings" "time" // Added for time.Now() - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/internal/utils" // Added for ID generation - "github.com/your-org/brain/control-plane/pkg/types" // Added for new types + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/internal/utils" // Added for ID generation + "github.com/your-org/haxen/control-plane/pkg/types" // Added for new types "github.com/gin-gonic/gin" ) @@ -37,8 +37,8 @@ func ExecuteReasonerHandler(storageProvider storage.StorageProvider) gin.Handler ctx := c.Request.Context() startTime := time.Now() - // Generate Brain Request ID - brainRequestID := utils.GenerateBrainRequestID() + // Generate Haxen Request ID + haxenRequestID := utils.GenerateHaxenRequestID() // Extract headers workflowID := c.GetHeader("X-Workflow-ID") @@ -122,7 +122,7 @@ func ExecuteReasonerHandler(storageProvider storage.StorageProvider) gin.Handler workflowExecution := &types.WorkflowExecution{ WorkflowID: workflowID, ExecutionID: executionID, - BrainRequestID: brainRequestID, + HaxenRequestID: haxenRequestID, AgentNodeID: nodeID, ReasonerID: reasonerName, Status: "running", @@ -189,7 +189,7 @@ func ExecuteReasonerHandler(storageProvider storage.StorageProvider) gin.Handler agentReq.Header.Set("Content-Type", "application/json") agentReq.Header.Set("X-Workflow-ID", workflowID) agentReq.Header.Set("X-Execution-ID", executionID) - agentReq.Header.Set("X-Brain-Request-ID", brainRequestID) + agentReq.Header.Set("X-Haxen-Request-ID", haxenRequestID) if parentWorkflowID != "" { agentReq.Header.Set("X-Parent-Workflow-ID", parentWorkflowID) } @@ -303,7 +303,7 @@ func ExecuteReasonerHandler(storageProvider storage.StorageProvider) gin.Handler // Set response headers c.Header("X-Workflow-ID", workflowID) c.Header("X-Execution-ID", executionID) - c.Header("X-Brain-Request-ID", brainRequestID) + c.Header("X-Haxen-Request-ID", haxenRequestID) c.Header("X-Agent-Node-ID", nodeID) c.Header("X-Duration-MS", fmt.Sprintf("%d", duration)) @@ -317,14 +317,14 @@ func ExecuteReasonerHandler(storageProvider storage.StorageProvider) gin.Handler } } -// ExecuteSkillHandler handles execution of skills via Brain server +// ExecuteSkillHandler handles execution of skills via Haxen server func ExecuteSkillHandler(storageProvider storage.StorageProvider) gin.HandlerFunc { return func(c *gin.Context) { ctx := c.Request.Context() startTime := time.Now() - // Generate Brain Request ID - brainRequestID := utils.GenerateBrainRequestID() + // Generate Haxen Request ID + haxenRequestID := utils.GenerateHaxenRequestID() // Extract headers workflowID := c.GetHeader("X-Workflow-ID") @@ -408,7 +408,7 @@ func ExecuteSkillHandler(storageProvider storage.StorageProvider) gin.HandlerFun workflowExecution := &types.WorkflowExecution{ WorkflowID: workflowID, ExecutionID: executionID, - BrainRequestID: brainRequestID, + HaxenRequestID: haxenRequestID, AgentNodeID: nodeID, ReasonerID: skillName, // For skills, ReasonerID will store skillName Status: "running", @@ -475,7 +475,7 @@ func ExecuteSkillHandler(storageProvider storage.StorageProvider) gin.HandlerFun agentReq.Header.Set("Content-Type", "application/json") agentReq.Header.Set("X-Workflow-ID", workflowID) agentReq.Header.Set("X-Execution-ID", executionID) - agentReq.Header.Set("X-Brain-Request-ID", brainRequestID) + agentReq.Header.Set("X-Haxen-Request-ID", haxenRequestID) if parentWorkflowID != "" { agentReq.Header.Set("X-Parent-Workflow-ID", parentWorkflowID) } @@ -589,7 +589,7 @@ func ExecuteSkillHandler(storageProvider storage.StorageProvider) gin.HandlerFun // Set response headers c.Header("X-Workflow-ID", workflowID) c.Header("X-Execution-ID", executionID) - c.Header("X-Brain-Request-ID", brainRequestID) + c.Header("X-Haxen-Request-ID", haxenRequestID) c.Header("X-Agent-Node-ID", nodeID) c.Header("X-Duration-MS", fmt.Sprintf("%d", duration)) diff --git a/control-plane/internal/handlers/test_helpers_test.go b/control-plane/internal/handlers/test_helpers_test.go index 287eed50..80bc9d15 100644 --- a/control-plane/internal/handlers/test_helpers_test.go +++ b/control-plane/internal/handlers/test_helpers_test.go @@ -6,8 +6,8 @@ import ( "sync" "time" - "github.com/your-org/brain/control-plane/internal/events" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/events" + "github.com/your-org/haxen/control-plane/pkg/types" ) type testExecutionStorage struct { diff --git a/control-plane/internal/handlers/ui/config.go b/control-plane/internal/handlers/ui/config.go index 7010209d..7a195160 100644 --- a/control-plane/internal/handlers/ui/config.go +++ b/control-plane/internal/handlers/ui/config.go @@ -4,8 +4,8 @@ import ( "encoding/json" "net/http" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" ) diff --git a/control-plane/internal/handlers/ui/config_test.go b/control-plane/internal/handlers/ui/config_test.go index dcae4e0f..3ed9425f 100644 --- a/control-plane/internal/handlers/ui/config_test.go +++ b/control-plane/internal/handlers/ui/config_test.go @@ -13,9 +13,9 @@ import ( "testing" "time" - "github.com/your-org/brain/control-plane/internal/events" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/events" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" @@ -454,31 +454,31 @@ func (m *MockStorageProvider) ListDIDs(ctx context.Context) ([]*types.DIDRegistr return args.Get(0).([]*types.DIDRegistryEntry), args.Error(1) } -// Brain Server DID operations -func (m *MockStorageProvider) StoreBrainServerDID(ctx context.Context, brainServerID, rootDID string, masterSeed []byte, createdAt, lastKeyRotation time.Time) error { - args := m.Called(ctx, brainServerID, rootDID, masterSeed, createdAt, lastKeyRotation) +// Haxen Server DID operations +func (m *MockStorageProvider) StoreHaxenServerDID(ctx context.Context, haxenServerID, rootDID string, masterSeed []byte, createdAt, lastKeyRotation time.Time) error { + args := m.Called(ctx, haxenServerID, rootDID, masterSeed, createdAt, lastKeyRotation) return args.Error(0) } -func (m *MockStorageProvider) GetBrainServerDID(ctx context.Context, brainServerID string) (*types.BrainServerDIDInfo, error) { - args := m.Called(ctx, brainServerID) +func (m *MockStorageProvider) GetHaxenServerDID(ctx context.Context, haxenServerID string) (*types.HaxenServerDIDInfo, error) { + args := m.Called(ctx, haxenServerID) if args.Get(0) == nil { return nil, args.Error(1) } - return args.Get(0).(*types.BrainServerDIDInfo), args.Error(1) + return args.Get(0).(*types.HaxenServerDIDInfo), args.Error(1) } -func (m *MockStorageProvider) ListBrainServerDIDs(ctx context.Context) ([]*types.BrainServerDIDInfo, error) { +func (m *MockStorageProvider) ListHaxenServerDIDs(ctx context.Context) ([]*types.HaxenServerDIDInfo, error) { args := m.Called(ctx) if args.Get(0) == nil { return nil, args.Error(1) } - return args.Get(0).([]*types.BrainServerDIDInfo), args.Error(1) + return args.Get(0).([]*types.HaxenServerDIDInfo), args.Error(1) } // Agent DID operations -func (m *MockStorageProvider) StoreAgentDID(ctx context.Context, agentID, agentDID, brainServerDID, publicKeyJWK string, derivationIndex int) error { - args := m.Called(ctx, agentID, agentDID, brainServerDID, publicKeyJWK, derivationIndex) +func (m *MockStorageProvider) StoreAgentDID(ctx context.Context, agentID, agentDID, haxenServerDID, publicKeyJWK string, derivationIndex int) error { + args := m.Called(ctx, agentID, agentDID, haxenServerDID, publicKeyJWK, derivationIndex) return args.Error(0) } diff --git a/control-plane/internal/handlers/ui/dashboard.go b/control-plane/internal/handlers/ui/dashboard.go index 18b5f228..8d295655 100644 --- a/control-plane/internal/handlers/ui/dashboard.go +++ b/control-plane/internal/handlers/ui/dashboard.go @@ -7,10 +7,10 @@ import ( "sync" "time" - "github.com/your-org/brain/control-plane/internal/core/interfaces" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/core/interfaces" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" ) diff --git a/control-plane/internal/handlers/ui/did.go b/control-plane/internal/handlers/ui/did.go index b0b0254c..898d637e 100644 --- a/control-plane/internal/handlers/ui/did.go +++ b/control-plane/internal/handlers/ui/did.go @@ -6,9 +6,9 @@ import ( "net/http" "time" - "github.com/your-org/brain/control-plane/internal/services" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/services" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" ) @@ -50,21 +50,21 @@ func (h *DIDHandler) GetNodeDIDHandler(c *gin.Context) { return } - // Get brain server ID dynamically - brainServerID, err := h.didService.GetBrainServerID() + // Get haxen server ID dynamically + haxenServerID, err := h.didService.GetHaxenServerID() if err != nil { c.JSON(http.StatusOK, gin.H{ "has_did": false, "did_status": "inactive", "reasoner_count": 0, "skill_count": 0, - "error": fmt.Sprintf("Failed to get brain server ID: %v", err), + "error": fmt.Sprintf("Failed to get haxen server ID: %v", err), }) return } - // Get DID registry for the brain server (not the node) - registry, err := h.didService.GetRegistry(brainServerID) + // Get DID registry for the haxen server (not the node) + registry, err := h.didService.GetRegistry(haxenServerID) if err != nil || registry == nil { c.JSON(http.StatusOK, gin.H{ "has_did": false, @@ -98,7 +98,7 @@ func (h *DIDHandler) GetNodeDIDHandler(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "did": agentInfo.DID, "agent_node_id": nodeID, - "brain_server_id": registry.BrainServerID, + "haxen_server_id": registry.HaxenServerID, "public_key_jwk": agentInfo.PublicKeyJWK, "derivation_path": agentInfo.DerivationPath, "reasoners": agentInfo.Reasoners, @@ -591,7 +591,7 @@ func (h *DIDHandler) GetDIDResolutionBundleHandler(c *gin.Context) { "component_dids": []interface{}{}, "resolution_metadata": gin.H{ "resolved_at": time.Now().Format(time.RFC3339), - "resolver": "brain-server", + "resolver": "haxen-server", "status": "inactive", }, }) @@ -633,7 +633,7 @@ func (h *DIDHandler) GetDIDResolutionBundleHandler(c *gin.Context) { { "id": did + "#agent-service", "type": "AgentService", - "serviceEndpoint": fmt.Sprintf("https://brain-server/agents/%s", agentDID.AgentNodeID), + "serviceEndpoint": fmt.Sprintf("https://haxen-server/agents/%s", agentDID.AgentNodeID), }, }, } @@ -651,7 +651,7 @@ func (h *DIDHandler) GetDIDResolutionBundleHandler(c *gin.Context) { serviceEndpoints = append(serviceEndpoints, gin.H{ "id": did + "#agent-service", "type": "AgentService", - "serviceEndpoint": fmt.Sprintf("https://brain-server/agents/%s", agentDID.AgentNodeID), + "serviceEndpoint": fmt.Sprintf("https://haxen-server/agents/%s", agentDID.AgentNodeID), }) // Add component DIDs (reasoners and skills) @@ -708,7 +708,7 @@ func (h *DIDHandler) GetDIDResolutionBundleHandler(c *gin.Context) { { "id": did + "#component-service", "type": fmt.Sprintf("%sService", componentDID.ComponentType), - "serviceEndpoint": fmt.Sprintf("https://brain-server/components/%s", componentDID.ComponentID), + "serviceEndpoint": fmt.Sprintf("https://haxen-server/components/%s", componentDID.ComponentID), }, }, } @@ -717,7 +717,7 @@ func (h *DIDHandler) GetDIDResolutionBundleHandler(c *gin.Context) { serviceEndpoints = append(serviceEndpoints, gin.H{ "id": did + "#component-service", "type": fmt.Sprintf("%sService", componentDID.ComponentType), - "serviceEndpoint": fmt.Sprintf("https://brain-server/components/%s", componentDID.ComponentID), + "serviceEndpoint": fmt.Sprintf("https://haxen-server/components/%s", componentDID.ComponentID), }) break @@ -753,9 +753,9 @@ func (h *DIDHandler) GetDIDResolutionBundleHandler(c *gin.Context) { // Build resolution metadata resolutionMetadata := gin.H{ "resolved_at": time.Now().Format(time.RFC3339), - "resolver": "brain-server", + "resolver": "haxen-server", "status": resolutionStatus, - "method": "brain", + "method": "haxen", } if resolutionStatus == "resolved" { @@ -801,8 +801,8 @@ func (h *DIDHandler) DownloadDIDResolutionBundleHandler(c *gin.Context) { "did": did, "resolution_metadata": gin.H{ "resolved_at": time.Now().Format(time.RFC3339), - "resolver": "brain-server", - "method": "brain", + "resolver": "haxen-server", + "method": "haxen", }, "bundle_type": "did_resolution", "generated_at": time.Now().Format(time.RFC3339), diff --git a/control-plane/internal/handlers/ui/env.go b/control-plane/internal/handlers/ui/env.go index 3983e061..558297a6 100644 --- a/control-plane/internal/handlers/ui/env.go +++ b/control-plane/internal/handlers/ui/env.go @@ -8,8 +8,8 @@ import ( "strings" "time" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/internal/core/interfaces" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/internal/core/interfaces" "github.com/gin-gonic/gin" ) @@ -18,7 +18,7 @@ import ( type EnvHandler struct { storage storage.StorageProvider agentService interfaces.AgentService - brainHome string + haxenHome string } // DELETE /api/ui/v1/agents/:agentId/env/:key @@ -241,11 +241,11 @@ type EnvResponse struct { } // NewEnvHandler creates a new EnvHandler. -func NewEnvHandler(storage storage.StorageProvider, agentService interfaces.AgentService, brainHome string) *EnvHandler { +func NewEnvHandler(storage storage.StorageProvider, agentService interfaces.AgentService, haxenHome string) *EnvHandler { return &EnvHandler{ storage: storage, agentService: agentService, - brainHome: brainHome, + haxenHome: haxenHome, } } diff --git a/control-plane/internal/handlers/ui/execution_timeline.go b/control-plane/internal/handlers/ui/execution_timeline.go index 82c20869..d9e598c8 100644 --- a/control-plane/internal/handlers/ui/execution_timeline.go +++ b/control-plane/internal/handlers/ui/execution_timeline.go @@ -7,9 +7,9 @@ import ( "sync" "time" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" ) diff --git a/control-plane/internal/handlers/ui/executions.go b/control-plane/internal/handlers/ui/executions.go index 51933953..f452ef87 100644 --- a/control-plane/internal/handlers/ui/executions.go +++ b/control-plane/internal/handlers/ui/executions.go @@ -11,10 +11,10 @@ import ( "strings" "time" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/internal/services" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/services" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" ) @@ -145,7 +145,7 @@ type ExecutionDetailsResponse struct { ID int64 `json:"id"` ExecutionID string `json:"execution_id"` WorkflowID string `json:"workflow_id"` - BrainRequestID *string `json:"brain_request_id,omitempty"` + HaxenRequestID *string `json:"haxen_request_id,omitempty"` SessionID *string `json:"session_id,omitempty"` ActorID *string `json:"actor_id,omitempty"` AgentNodeID string `json:"agent_node_id"` @@ -691,7 +691,7 @@ func (h *ExecutionHandler) toExecutionDetails(ctx context.Context, exec *types.E ID: 0, ExecutionID: exec.ExecutionID, WorkflowID: exec.RunID, - BrainRequestID: nil, + HaxenRequestID: nil, SessionID: exec.SessionID, ActorID: exec.ActorID, AgentNodeID: exec.AgentNodeID, diff --git a/control-plane/internal/handlers/ui/executions_helpers_test.go b/control-plane/internal/handlers/ui/executions_helpers_test.go index 150a4dcb..ddb058f4 100644 --- a/control-plane/internal/handlers/ui/executions_helpers_test.go +++ b/control-plane/internal/handlers/ui/executions_helpers_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/your-org/brain/control-plane/internal/services" + "github.com/your-org/haxen/control-plane/internal/services" ) type testPayloadStore struct { diff --git a/control-plane/internal/handlers/ui/executions_test.go b/control-plane/internal/handlers/ui/executions_test.go index 0c98d283..a49c9a2b 100644 --- a/control-plane/internal/handlers/ui/executions_test.go +++ b/control-plane/internal/handlers/ui/executions_test.go @@ -14,8 +14,8 @@ import ( "testing" "time" - "github.com/your-org/brain/control-plane/internal/services" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/services" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" diff --git a/control-plane/internal/handlers/ui/lifecycle.go b/control-plane/internal/handlers/ui/lifecycle.go index 1cabff79..93076fe7 100644 --- a/control-plane/internal/handlers/ui/lifecycle.go +++ b/control-plane/internal/handlers/ui/lifecycle.go @@ -6,10 +6,10 @@ import ( "strconv" "strings" - "github.com/your-org/brain/control-plane/internal/core/domain" - "github.com/your-org/brain/control-plane/internal/core/interfaces" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/core/domain" + "github.com/your-org/haxen/control-plane/internal/core/interfaces" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" ) diff --git a/control-plane/internal/handlers/ui/mcp.go b/control-plane/internal/handlers/ui/mcp.go index eec9c29b..fe160bac 100644 --- a/control-plane/internal/handlers/ui/mcp.go +++ b/control-plane/internal/handlers/ui/mcp.go @@ -4,9 +4,9 @@ import ( "net/http" "time" - "github.com/your-org/brain/control-plane/internal/core/domain" - "github.com/your-org/brain/control-plane/internal/core/interfaces" - "github.com/your-org/brain/control-plane/internal/services" + "github.com/your-org/haxen/control-plane/internal/core/domain" + "github.com/your-org/haxen/control-plane/internal/core/interfaces" + "github.com/your-org/haxen/control-plane/internal/services" "github.com/gin-gonic/gin" ) diff --git a/control-plane/internal/handlers/ui/nodes.go b/control-plane/internal/handlers/ui/nodes.go index de8883c7..725820d5 100644 --- a/control-plane/internal/handlers/ui/nodes.go +++ b/control-plane/internal/handlers/ui/nodes.go @@ -6,9 +6,9 @@ import ( "net/http" "time" - "github.com/your-org/brain/control-plane/internal/events" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/internal/services" + "github.com/your-org/haxen/control-plane/internal/events" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/services" "github.com/gin-gonic/gin" ) diff --git a/control-plane/internal/handlers/ui/packages.go b/control-plane/internal/handlers/ui/packages.go index df995df1..ef6a3d53 100644 --- a/control-plane/internal/handlers/ui/packages.go +++ b/control-plane/internal/handlers/ui/packages.go @@ -6,8 +6,8 @@ import ( "net/http" "strings" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" ) diff --git a/control-plane/internal/handlers/ui/packages_test.go b/control-plane/internal/handlers/ui/packages_test.go index c4b54c0b..954c15dd 100644 --- a/control-plane/internal/handlers/ui/packages_test.go +++ b/control-plane/internal/handlers/ui/packages_test.go @@ -9,7 +9,7 @@ import ( "net/http/httptest" "testing" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" diff --git a/control-plane/internal/handlers/ui/reasoners.go b/control-plane/internal/handlers/ui/reasoners.go index 069a6a4c..70a77eb2 100644 --- a/control-plane/internal/handlers/ui/reasoners.go +++ b/control-plane/internal/handlers/ui/reasoners.go @@ -8,9 +8,9 @@ import ( "strings" "time" - "github.com/your-org/brain/control-plane/internal/events" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/events" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" ) diff --git a/control-plane/internal/handlers/ui/recent_activity.go b/control-plane/internal/handlers/ui/recent_activity.go index 76b4f3dd..f91cedc6 100644 --- a/control-plane/internal/handlers/ui/recent_activity.go +++ b/control-plane/internal/handlers/ui/recent_activity.go @@ -7,9 +7,9 @@ import ( "sync" "time" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" ) diff --git a/control-plane/internal/handlers/ui/workflow_runs.go b/control-plane/internal/handlers/ui/workflow_runs.go index 003f04f2..85151ef4 100644 --- a/control-plane/internal/handlers/ui/workflow_runs.go +++ b/control-plane/internal/handlers/ui/workflow_runs.go @@ -7,9 +7,9 @@ import ( "strings" "time" - "github.com/your-org/brain/control-plane/internal/handlers" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/handlers" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" ) diff --git a/control-plane/internal/handlers/utils.go b/control-plane/internal/handlers/utils.go index 07ccce31..2798b2aa 100644 --- a/control-plane/internal/handlers/utils.go +++ b/control-plane/internal/handlers/utils.go @@ -4,7 +4,7 @@ import ( "encoding/json" "fmt" - "github.com/your-org/brain/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/logger" ) // marshalDataWithLogging marshals data to JSON with proper error handling and logging diff --git a/control-plane/internal/handlers/workflow_cleanup.go b/control-plane/internal/handlers/workflow_cleanup.go index ddd51a7b..060165ea 100644 --- a/control-plane/internal/handlers/workflow_cleanup.go +++ b/control-plane/internal/handlers/workflow_cleanup.go @@ -4,7 +4,7 @@ import ( "net/http" "strings" - "github.com/your-org/brain/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/internal/storage" "github.com/gin-gonic/gin" ) diff --git a/control-plane/internal/handlers/workflow_cleanup_test.go b/control-plane/internal/handlers/workflow_cleanup_test.go index 8696677f..f46f6630 100644 --- a/control-plane/internal/handlers/workflow_cleanup_test.go +++ b/control-plane/internal/handlers/workflow_cleanup_test.go @@ -9,7 +9,7 @@ import ( "net/http/httptest" "testing" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" diff --git a/control-plane/internal/handlers/workflow_dag.go b/control-plane/internal/handlers/workflow_dag.go index c6a30dc6..7b154c1b 100644 --- a/control-plane/internal/handlers/workflow_dag.go +++ b/control-plane/internal/handlers/workflow_dag.go @@ -8,8 +8,8 @@ import ( "strings" "time" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/gin-gonic/gin" ) diff --git a/control-plane/internal/infrastructure/communication/agent_client.go b/control-plane/internal/infrastructure/communication/agent_client.go index f25b07b7..68b4340b 100644 --- a/control-plane/internal/infrastructure/communication/agent_client.go +++ b/control-plane/internal/infrastructure/communication/agent_client.go @@ -10,8 +10,8 @@ import ( "sync" "time" - "github.com/your-org/brain/control-plane/internal/core/interfaces" - "github.com/your-org/brain/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/internal/core/interfaces" + "github.com/your-org/haxen/control-plane/internal/storage" ) // HTTPAgentClient implements the AgentClient interface using HTTP communication @@ -72,7 +72,7 @@ func (c *HTTPAgentClient) GetMCPHealth(ctx context.Context, nodeID string) (*int // Set headers req.Header.Set("Content-Type", "application/json") - req.Header.Set("User-Agent", "Brain-Server/1.0") + req.Header.Set("User-Agent", "Haxen-Server/1.0") // Make the request resp, err := c.httpClient.Do(req) @@ -130,7 +130,7 @@ func (c *HTTPAgentClient) RestartMCPServer(ctx context.Context, nodeID, alias st // Set headers req.Header.Set("Content-Type", "application/json") - req.Header.Set("User-Agent", "Brain-Server/1.0") + req.Header.Set("User-Agent", "Haxen-Server/1.0") // Make the request resp, err := c.httpClient.Do(req) @@ -183,7 +183,7 @@ func (c *HTTPAgentClient) GetMCPTools(ctx context.Context, nodeID, alias string) // Set headers req.Header.Set("Content-Type", "application/json") - req.Header.Set("User-Agent", "Brain-Server/1.0") + req.Header.Set("User-Agent", "Haxen-Server/1.0") // Make the request resp, err := c.httpClient.Do(req) @@ -241,7 +241,7 @@ func (c *HTTPAgentClient) ShutdownAgent(ctx context.Context, nodeID string, grac // Set headers req.Header.Set("Content-Type", "application/json") - req.Header.Set("User-Agent", "Brain-Server/1.0") + req.Header.Set("User-Agent", "Haxen-Server/1.0") // Make the request resp, err := c.httpClient.Do(req) @@ -301,7 +301,7 @@ func (c *HTTPAgentClient) GetAgentStatus(ctx context.Context, nodeID string) (*i // Set headers req.Header.Set("Content-Type", "application/json") - req.Header.Set("User-Agent", "Brain-Server/1.0") + req.Header.Set("User-Agent", "Haxen-Server/1.0") // Make the request resp, err := c.httpClient.Do(req) diff --git a/control-plane/internal/infrastructure/process/manager.go b/control-plane/internal/infrastructure/process/manager.go index 1f749fe9..6213a366 100644 --- a/control-plane/internal/infrastructure/process/manager.go +++ b/control-plane/internal/infrastructure/process/manager.go @@ -7,7 +7,7 @@ import ( "path/filepath" "syscall" - "github.com/your-org/brain/control-plane/internal/core/interfaces" + "github.com/your-org/haxen/control-plane/internal/core/interfaces" ) // DefaultProcessManager provides a default implementation for managing system processes. diff --git a/control-plane/internal/infrastructure/process/port_manager.go b/control-plane/internal/infrastructure/process/port_manager.go index ae8c7238..efbc0c58 100644 --- a/control-plane/internal/infrastructure/process/port_manager.go +++ b/control-plane/internal/infrastructure/process/port_manager.go @@ -1,11 +1,11 @@ -// brain/internal/infrastructure/process/port_manager.go +// haxen/internal/infrastructure/process/port_manager.go package process import ( "fmt" "net" - "github.com/your-org/brain/control-plane/internal/core/interfaces" + "github.com/your-org/haxen/control-plane/internal/core/interfaces" ) // DefaultPortManager provides a default implementation for managing network ports. diff --git a/control-plane/internal/infrastructure/storage/config.go b/control-plane/internal/infrastructure/storage/config.go index 4dd221b4..1d71cee1 100644 --- a/control-plane/internal/infrastructure/storage/config.go +++ b/control-plane/internal/infrastructure/storage/config.go @@ -1,11 +1,11 @@ -// brain/internal/infrastructure/storage/config.go +// haxen/internal/infrastructure/storage/config.go package storage import ( "os" "path/filepath" - "github.com/your-org/brain/control-plane/internal/core/domain" - "github.com/your-org/brain/control-plane/internal/core/interfaces" + "github.com/your-org/haxen/control-plane/internal/core/domain" + "github.com/your-org/haxen/control-plane/internal/core/interfaces" "gopkg.in/yaml.v3" ) @@ -17,9 +17,9 @@ func NewLocalConfigStorage(fs interfaces.FileSystemAdapter) interfaces.ConfigSto return &LocalConfigStorage{fs: fs} } -func (s *LocalConfigStorage) LoadBrainConfig(path string) (*domain.BrainConfig, error) { +func (s *LocalConfigStorage) LoadHaxenConfig(path string) (*domain.HaxenConfig, error) { if !s.fs.Exists(path) { - return &domain.BrainConfig{ + return &domain.HaxenConfig{ HomeDir: filepath.Dir(path), Environment: make(map[string]string), MCP: domain.MCPConfig{ @@ -33,7 +33,7 @@ func (s *LocalConfigStorage) LoadBrainConfig(path string) (*domain.BrainConfig, return nil, err } - var config domain.BrainConfig + var config domain.HaxenConfig if err := yaml.Unmarshal(data, &config); err != nil { return nil, err } @@ -41,7 +41,7 @@ func (s *LocalConfigStorage) LoadBrainConfig(path string) (*domain.BrainConfig, return &config, nil } -func (s *LocalConfigStorage) SaveBrainConfig(path string, config *domain.BrainConfig) error { +func (s *LocalConfigStorage) SaveHaxenConfig(path string, config *domain.HaxenConfig) error { data, err := yaml.Marshal(config) if err != nil { return err diff --git a/control-plane/internal/infrastructure/storage/filesystem.go b/control-plane/internal/infrastructure/storage/filesystem.go index 90172616..9c4cf9d3 100644 --- a/control-plane/internal/infrastructure/storage/filesystem.go +++ b/control-plane/internal/infrastructure/storage/filesystem.go @@ -1,9 +1,9 @@ -// brain/internal/infrastructure/storage/filesystem.go +// haxen/internal/infrastructure/storage/filesystem.go package storage import ( "os" - "github.com/your-org/brain/control-plane/internal/core/interfaces" + "github.com/your-org/haxen/control-plane/internal/core/interfaces" ) type DefaultFileSystemAdapter struct{} diff --git a/control-plane/internal/infrastructure/storage/registry.go b/control-plane/internal/infrastructure/storage/registry.go index 5d4c0a60..0fc8ef88 100644 --- a/control-plane/internal/infrastructure/storage/registry.go +++ b/control-plane/internal/infrastructure/storage/registry.go @@ -1,12 +1,12 @@ -// brain/internal/infrastructure/storage/registry.go +// haxen/internal/infrastructure/storage/registry.go package storage import ( "encoding/json" "os" "path/filepath" - "github.com/your-org/brain/control-plane/internal/core/domain" - "github.com/your-org/brain/control-plane/internal/core/interfaces" + "github.com/your-org/haxen/control-plane/internal/core/domain" + "github.com/your-org/haxen/control-plane/internal/core/interfaces" ) type LocalRegistryStorage struct { diff --git a/control-plane/internal/logger/logger.go b/control-plane/internal/logger/logger.go index 1b351173..c2704a8b 100644 --- a/control-plane/internal/logger/logger.go +++ b/control-plane/internal/logger/logger.go @@ -1,4 +1,4 @@ -// Package logger provides a global zerolog logger for the Brain CLI. +// Package logger provides a global zerolog logger for the Haxen CLI. package logger import ( diff --git a/control-plane/internal/mcp/capability_discovery.go b/control-plane/internal/mcp/capability_discovery.go index 747fde39..6b1c28db 100644 --- a/control-plane/internal/mcp/capability_discovery.go +++ b/control-plane/internal/mcp/capability_discovery.go @@ -13,7 +13,7 @@ import ( "syscall" "time" - "github.com/your-org/brain/control-plane/internal/config" + "github.com/your-org/haxen/control-plane/internal/config" ) // MCPCapability represents a discovered MCP server capability @@ -182,7 +182,7 @@ func (cd *CapabilityDiscovery) discoverServerCapability(serverAlias string) (*MC // Read config.json metadata file metadataBytes, err := os.ReadFile(metadataPath) if err != nil { - return nil, fmt.Errorf("failed to read config.json (try running: brain mcp migrate %s): %w", serverAlias, err) + return nil, fmt.Errorf("failed to read config.json (try running: haxen mcp migrate %s): %w", serverAlias, err) } var metadata MCPServerConfig @@ -627,7 +627,7 @@ func (cd *CapabilityDiscovery) performDiscoveryWithPipes(ctx context.Context, st }, }, ClientInfo: ClientInfo{ - Name: "brain-mcp-client", + Name: "haxen-mcp-client", Version: "1.0.0", }, }, diff --git a/control-plane/internal/mcp/manager.go b/control-plane/internal/mcp/manager.go index 346f0f8d..c1cf479f 100644 --- a/control-plane/internal/mcp/manager.go +++ b/control-plane/internal/mcp/manager.go @@ -8,7 +8,7 @@ import ( "path/filepath" "time" - "github.com/your-org/brain/control-plane/internal/config" + "github.com/your-org/haxen/control-plane/internal/config" "gopkg.in/yaml.v3" ) @@ -89,9 +89,9 @@ func (m *MCPManager) Add(config MCPServerConfig) error { return fmt.Errorf("failed to save configuration: %w", err) } - // Update brain.yaml - if err := m.updateBrainYAML(config); err != nil { - return fmt.Errorf("failed to update brain.yaml: %w", err) + // Update haxen.yaml + if err := m.updateHaxenYAML(config); err != nil { + return fmt.Errorf("failed to update haxen.yaml: %w", err) } // Attempt to start and discover capabilities @@ -243,9 +243,9 @@ func (m *MCPManager) Remove(alias string) error { return fmt.Errorf("failed to remove server directory: %w", err) } - // Update brain.yaml - if err := m.removeMCPFromBrainYAML(alias); err != nil { - return fmt.Errorf("failed to update brain.yaml: %w", err) + // Update haxen.yaml + if err := m.removeMCPFromHaxenYAML(alias); err != nil { + return fmt.Errorf("failed to update haxen.yaml: %w", err) } if m.verbose { @@ -399,20 +399,20 @@ func (m *MCPManager) getServerInfo(alias string) (*MCPServerInfo, error) { return info, nil } -// updateBrainYAML updates the brain.yaml file with the new MCP server -func (m *MCPManager) updateBrainYAML(config MCPServerConfig) error { - brainYAMLPath := filepath.Join(m.projectDir, "brain.yaml") +// updateHaxenYAML updates the haxen.yaml file with the new MCP server +func (m *MCPManager) updateHaxenYAML(config MCPServerConfig) error { + haxenYAMLPath := filepath.Join(m.projectDir, "haxen.yaml") - // Read existing brain.yaml - data, err := os.ReadFile(brainYAMLPath) + // Read existing haxen.yaml + data, err := os.ReadFile(haxenYAMLPath) if err != nil { - return fmt.Errorf("failed to read brain.yaml: %w", err) + return fmt.Errorf("failed to read haxen.yaml: %w", err) } // Parse YAML var yamlConfig map[string]interface{} if err := yaml.Unmarshal(data, &yamlConfig); err != nil { - return fmt.Errorf("failed to parse brain.yaml: %w", err) + return fmt.Errorf("failed to parse haxen.yaml: %w", err) } // Ensure dependencies section exists @@ -474,30 +474,30 @@ func (m *MCPManager) updateBrainYAML(config MCPServerConfig) error { // Write back to file updatedData, err := yaml.Marshal(yamlConfig) if err != nil { - return fmt.Errorf("failed to marshal brain.yaml: %w", err) + return fmt.Errorf("failed to marshal haxen.yaml: %w", err) } - if err := os.WriteFile(brainYAMLPath, updatedData, 0644); err != nil { - return fmt.Errorf("failed to write brain.yaml: %w", err) + if err := os.WriteFile(haxenYAMLPath, updatedData, 0644); err != nil { + return fmt.Errorf("failed to write haxen.yaml: %w", err) } return nil } -// removeMCPFromBrainYAML removes an MCP server from brain.yaml -func (m *MCPManager) removeMCPFromBrainYAML(alias string) error { - brainYAMLPath := filepath.Join(m.projectDir, "brain.yaml") +// removeMCPFromHaxenYAML removes an MCP server from haxen.yaml +func (m *MCPManager) removeMCPFromHaxenYAML(alias string) error { + haxenYAMLPath := filepath.Join(m.projectDir, "haxen.yaml") - // Read existing brain.yaml - data, err := os.ReadFile(brainYAMLPath) + // Read existing haxen.yaml + data, err := os.ReadFile(haxenYAMLPath) if err != nil { - return fmt.Errorf("failed to read brain.yaml: %w", err) + return fmt.Errorf("failed to read haxen.yaml: %w", err) } // Parse YAML var config map[string]interface{} if err := yaml.Unmarshal(data, &config); err != nil { - return fmt.Errorf("failed to parse brain.yaml: %w", err) + return fmt.Errorf("failed to parse haxen.yaml: %w", err) } // Navigate to mcp_servers section @@ -510,28 +510,28 @@ func (m *MCPManager) removeMCPFromBrainYAML(alias string) error { // Write back to file updatedData, err := yaml.Marshal(config) if err != nil { - return fmt.Errorf("failed to marshal brain.yaml: %w", err) + return fmt.Errorf("failed to marshal haxen.yaml: %w", err) } - if err := os.WriteFile(brainYAMLPath, updatedData, 0644); err != nil { - return fmt.Errorf("failed to write brain.yaml: %w", err) + if err := os.WriteFile(haxenYAMLPath, updatedData, 0644); err != nil { + return fmt.Errorf("failed to write haxen.yaml: %w", err) } return nil } -// loadMCPConfigsFromYAML loads MCP configurations from brain.yaml +// loadMCPConfigsFromYAML loads MCP configurations from haxen.yaml func (m *MCPManager) loadMCPConfigsFromYAML() (map[string]MCPServerConfig, error) { - brainYAMLPath := filepath.Join(m.projectDir, "brain.yaml") + haxenYAMLPath := filepath.Join(m.projectDir, "haxen.yaml") - data, err := os.ReadFile(brainYAMLPath) + data, err := os.ReadFile(haxenYAMLPath) if err != nil { - return nil, fmt.Errorf("failed to read brain.yaml: %w", err) + return nil, fmt.Errorf("failed to read haxen.yaml: %w", err) } var config map[string]interface{} if err := yaml.Unmarshal(data, &config); err != nil { - return nil, fmt.Errorf("failed to parse brain.yaml: %w", err) + return nil, fmt.Errorf("failed to parse haxen.yaml: %w", err) } configs := make(map[string]MCPServerConfig) @@ -637,7 +637,7 @@ func (m *MCPManager) DiscoverCapabilities(alias string) (*MCPManifest, error) { if m.verbose { fmt.Printf("Successfully discovered capabilities for %s: %d tools, %d resources\n", alias, len(manifest.Tools), len(manifest.Resources)) - fmt.Printf("Note: MCP skills will be auto-registered by Brain SDK when agent starts\n") + fmt.Printf("Note: MCP skills will be auto-registered by Haxen SDK when agent starts\n") } return manifest, nil diff --git a/control-plane/internal/mcp/protocol_client.go b/control-plane/internal/mcp/protocol_client.go index 2c893096..c49f0080 100644 --- a/control-plane/internal/mcp/protocol_client.go +++ b/control-plane/internal/mcp/protocol_client.go @@ -164,7 +164,7 @@ func (client *MCPProtocolClient) sendInitialize(stdin io.Writer) error { "resources": map[string]interface{}{}, }, "clientInfo": map[string]interface{}{ - "name": "brain-mcp-client", + "name": "haxen-mcp-client", "version": "1.0.0", }, }, diff --git a/control-plane/internal/mcp/skill_generator.go b/control-plane/internal/mcp/skill_generator.go index 92bec7cf..2193c253 100644 --- a/control-plane/internal/mcp/skill_generator.go +++ b/control-plane/internal/mcp/skill_generator.go @@ -8,7 +8,7 @@ import ( "text/template" "time" - "github.com/your-org/brain/control-plane/internal/config" + "github.com/your-org/haxen/control-plane/internal/config" ) // SkillGenerator handles the generation of Python skill files from MCP tools @@ -41,12 +41,12 @@ func (sg *SkillGenerator) GenerateSkillsForServer(serverAlias string) (*SkillGen // Discover server capabilities using the new simplified architecture // Load config for capability discovery - cfg, err := config.LoadConfig(filepath.Join(sg.projectDir, "brain.yaml")) + cfg, err := config.LoadConfig(filepath.Join(sg.projectDir, "haxen.yaml")) if err != nil { // Fallback to current directory - cfg, err = config.LoadConfig("brain.yaml") + cfg, err = config.LoadConfig("haxen.yaml") if err != nil { - return nil, fmt.Errorf("failed to load brain configuration: %w", err) + return nil, fmt.Errorf("failed to load haxen configuration: %w", err) } } @@ -161,12 +161,12 @@ func getMapKeys(m map[string]interface{}) []string { // GenerateSkillsForAllServers generates skill files for all installed MCP servers func (sg *SkillGenerator) GenerateSkillsForAllServers() error { // Load config for capability discovery - cfg, err := config.LoadConfig(filepath.Join(sg.projectDir, "brain.yaml")) + cfg, err := config.LoadConfig(filepath.Join(sg.projectDir, "haxen.yaml")) if err != nil { // Fallback to current directory - cfg, err = config.LoadConfig("brain.yaml") + cfg, err = config.LoadConfig("haxen.yaml") if err != nil { - return fmt.Errorf("failed to load brain configuration: %w", err) + return fmt.Errorf("failed to load haxen configuration: %w", err) } } @@ -476,7 +476,7 @@ func (sg *SkillGenerator) generateDocString(tool MCPTool, parameters []SkillPara } docString.WriteString(` - execution_context (ExecutionContext, optional): Brain execution context for workflow tracking + execution_context (ExecutionContext, optional): Haxen execution context for workflow tracking Returns: Any: The result from the MCP tool execution @@ -499,13 +499,13 @@ Do not modify this file manually - it will be regenerated when the MCP server is """ from typing import Any, Dict, List, Optional -from brain_sdk import app -from brain_sdk.execution_context import ExecutionContext -from brain_sdk.mcp.client import MCPClient -from brain_sdk.mcp.exceptions import ( +from haxen_sdk import app +from haxen_sdk.execution_context import ExecutionContext +from haxen_sdk.mcp.client import MCPClient +from haxen_sdk.mcp.exceptions import ( MCPError, MCPConnectionError, MCPToolError, MCPTimeoutError ) -from brain_sdk.agent import Agent +from haxen_sdk.agent import Agent # MCP server configuration MCP_ALIAS = "{{.ServerAlias}}" @@ -533,7 +533,7 @@ async def _get_mcp_client(execution_context: Optional[ExecutionContext] = None) is_healthy = await client.validate_server_health() if not is_healthy: raise MCPConnectionError( - f"MCP server '{MCP_ALIAS}' is not healthy. Please check server status with: brain mcp status {MCP_ALIAS}", + f"MCP server '{MCP_ALIAS}' is not healthy. Please check server status with: haxen mcp status {MCP_ALIAS}", endpoint=f"mcp://{MCP_ALIAS}" ) @@ -551,7 +551,7 @@ async def _get_mcp_client(execution_context: Optional[ExecutionContext] = None) except ValueError as e: # Handle unregistered alias raise MCPConnectionError( - f"MCP server '{MCP_ALIAS}' is not configured. Please install it with: brain add --mcp {MCP_ALIAS}", + f"MCP server '{MCP_ALIAS}' is not configured. Please install it with: haxen add --mcp {MCP_ALIAS}", endpoint=f"mcp://{MCP_ALIAS}" ) from e except Exception as e: diff --git a/control-plane/internal/mcp/stdio_client.go b/control-plane/internal/mcp/stdio_client.go index 1118197b..324ec9cd 100644 --- a/control-plane/internal/mcp/stdio_client.go +++ b/control-plane/internal/mcp/stdio_client.go @@ -125,7 +125,7 @@ func (c *StdioMCPClient) performDiscovery(stdin io.WriteCloser, stdout io.ReadCl }, }, ClientInfo: ClientInfo{ - Name: "brain-mcp-client", + Name: "haxen-mcp-client", Version: "1.0.0", }, }, diff --git a/control-plane/internal/mcp/storage.go b/control-plane/internal/mcp/storage.go index ce8f3d61..2276e450 100644 --- a/control-plane/internal/mcp/storage.go +++ b/control-plane/internal/mcp/storage.go @@ -31,7 +31,7 @@ type ConfigStorage interface { } // YAMLConfigStorage implements ConfigStorage using a YAML file. -// It stores all MCP server configurations in a single brain.yaml file +// It stores all MCP server configurations in a single haxen.yaml file // under the dependencies.mcp_servers key. type YAMLConfigStorage struct { ProjectDir string @@ -40,30 +40,30 @@ type YAMLConfigStorage struct { } // NewYAMLConfigStorage creates a new YAMLConfigStorage. -// projectDir is the root directory of the brain project. +// projectDir is the root directory of the haxen project. func NewYAMLConfigStorage(projectDir string) *YAMLConfigStorage { return &YAMLConfigStorage{ ProjectDir: projectDir, - filePath: filepath.Join(projectDir, "brain.yaml"), + filePath: filepath.Join(projectDir, "haxen.yaml"), } } -// brainYAML represents the structure of the brain.yaml file. +// haxenYAML represents the structure of the haxen.yaml file. // We only care about the mcp_servers part for this storage. -type brainYAML struct { +type haxenYAML struct { Dependencies struct { MCPServers map[string]*MCPServerConfig `yaml:"mcp_servers,omitempty"` } `yaml:"dependencies,omitempty"` - // Other fields in brain.yaml are preserved but not directly managed here. + // Other fields in haxen.yaml are preserved but not directly managed here. OtherFields map[string]interface{} `yaml:",inline"` } -func (s *YAMLConfigStorage) loadBrainYAML() (*brainYAML, error) { +func (s *YAMLConfigStorage) loadHaxenYAML() (*haxenYAML, error) { data, err := os.ReadFile(s.filePath) if err != nil { if os.IsNotExist(err) { - // If brain.yaml doesn't exist, return an empty structure - return &brainYAML{ + // If haxen.yaml doesn't exist, return an empty structure + return &haxenYAML{ Dependencies: struct { MCPServers map[string]*MCPServerConfig `yaml:"mcp_servers,omitempty"` }{ @@ -72,24 +72,24 @@ func (s *YAMLConfigStorage) loadBrainYAML() (*brainYAML, error) { OtherFields: make(map[string]interface{}), }, nil } - return nil, fmt.Errorf("failed to read brain.yaml: %w", err) + return nil, fmt.Errorf("failed to read haxen.yaml: %w", err) } - var cfg brainYAML + var cfg haxenYAML // Initialize maps to avoid nil panics if sections are missing cfg.Dependencies.MCPServers = make(map[string]*MCPServerConfig) cfg.OtherFields = make(map[string]interface{}) if err := yaml.Unmarshal(data, &cfg); err != nil { - return nil, fmt.Errorf("failed to unmarshal brain.yaml: %w", err) + return nil, fmt.Errorf("failed to unmarshal haxen.yaml: %w", err) } return &cfg, nil } -func (s *YAMLConfigStorage) saveBrainYAML(cfg *brainYAML) error { +func (s *YAMLConfigStorage) saveHaxenYAML(cfg *haxenYAML) error { data, err := yaml.Marshal(cfg) if err != nil { - return fmt.Errorf("failed to marshal brain.yaml: %w", err) + return fmt.Errorf("failed to marshal haxen.yaml: %w", err) } return os.WriteFile(s.filePath, data, 0644) } @@ -99,7 +99,7 @@ func (s *YAMLConfigStorage) LoadMCPServerConfig(alias string) (*MCPServerConfig, s.mu.RLock() defer s.mu.RUnlock() - cfg, err := s.loadBrainYAML() + cfg, err := s.loadHaxenYAML() if err != nil { return nil, err } @@ -116,7 +116,7 @@ func (s *YAMLConfigStorage) SaveMCPServerConfig(alias string, config *MCPServerC s.mu.Lock() defer s.mu.Unlock() - cfg, err := s.loadBrainYAML() + cfg, err := s.loadHaxenYAML() if err != nil { return err } @@ -126,7 +126,7 @@ func (s *YAMLConfigStorage) SaveMCPServerConfig(alias string, config *MCPServerC } cfg.Dependencies.MCPServers[alias] = config - return s.saveBrainYAML(cfg) + return s.saveHaxenYAML(cfg) } // DeleteMCPServerConfig removes the configuration for a specific MCP server. @@ -134,7 +134,7 @@ func (s *YAMLConfigStorage) DeleteMCPServerConfig(alias string) error { s.mu.Lock() defer s.mu.Unlock() - cfg, err := s.loadBrainYAML() + cfg, err := s.loadHaxenYAML() if err != nil { return err } @@ -144,7 +144,7 @@ func (s *YAMLConfigStorage) DeleteMCPServerConfig(alias string) error { } delete(cfg.Dependencies.MCPServers, alias) - return s.saveBrainYAML(cfg) + return s.saveHaxenYAML(cfg) } // LoadAllMCPServerConfigs retrieves all stored MCP server configurations. @@ -152,7 +152,7 @@ func (s *YAMLConfigStorage) LoadAllMCPServerConfigs() (map[string]*MCPServerConf s.mu.RLock() defer s.mu.RUnlock() - cfg, err := s.loadBrainYAML() + cfg, err := s.loadHaxenYAML() if err != nil { return nil, err } @@ -169,7 +169,7 @@ func (s *YAMLConfigStorage) UpdateConfig(alias string, updateFn func(currentConf s.mu.Lock() defer s.mu.Unlock() - cfg, err := s.loadBrainYAML() + cfg, err := s.loadHaxenYAML() if err != nil { return err } @@ -195,7 +195,7 @@ func (s *YAMLConfigStorage) UpdateConfig(alias string, updateFn func(currentConf cfg.Dependencies.MCPServers[alias] = newConfig } - return s.saveBrainYAML(cfg) + return s.saveHaxenYAML(cfg) } // ListMCPServerAliases retrieves a list of all configured MCP server aliases. @@ -203,7 +203,7 @@ func (s *YAMLConfigStorage) ListMCPServerAliases() ([]string, error) { s.mu.RLock() defer s.mu.RUnlock() - cfg, err := s.loadBrainYAML() + cfg, err := s.loadHaxenYAML() if err != nil { return nil, err } diff --git a/control-plane/internal/packages/git.go b/control-plane/internal/packages/git.go index 8f3d9af5..c4e50651 100644 --- a/control-plane/internal/packages/git.go +++ b/control-plane/internal/packages/git.go @@ -9,7 +9,7 @@ import ( "strings" "time" - "github.com/your-org/brain/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/logger" "gopkg.in/yaml.v3" ) @@ -22,7 +22,7 @@ type GitPackageInfo struct { // GitInstaller handles Git package installation from any Git repository type GitInstaller struct { - BrainHome string + HaxenHome string Verbose bool } @@ -154,7 +154,7 @@ func (gi *GitInstaller) InstallFromGit(gitURL string, force bool) error { // 4. Use existing installer for the rest installer := &PackageInstaller{ - BrainHome: gi.BrainHome, + HaxenHome: gi.HaxenHome, Verbose: gi.Verbose, } @@ -164,7 +164,7 @@ func (gi *GitInstaller) InstallFromGit(gitURL string, force bool) error { } // Install using existing flow - destPath := filepath.Join(gi.BrainHome, "packages", metadata.Name) + destPath := filepath.Join(gi.HaxenHome, "packages", metadata.Name) spinner = gi.newSpinner("Setting up environment") spinner.Start() @@ -197,7 +197,7 @@ func (gi *GitInstaller) InstallFromGit(gitURL string, force bool) error { // Check for required environment variables installer.checkEnvironmentVariables(metadata) - logger.Logger.Info().Msgf("\n%s %s", Blue("→"), Bold(fmt.Sprintf("Run: brain run %s", metadata.Name))) + logger.Logger.Info().Msgf("\n%s %s", Blue("→"), Bold(fmt.Sprintf("Run: haxen run %s", metadata.Name))) return nil } @@ -205,7 +205,7 @@ func (gi *GitInstaller) InstallFromGit(gitURL string, force bool) error { // cloneRepository clones the Git repository with optimizations func (gi *GitInstaller) cloneRepository(info *GitPackageInfo) (string, error) { // Create temporary directory - tempDir, err := os.MkdirTemp("", "brain-git-install-") + tempDir, err := os.MkdirTemp("", "haxen-git-install-") if err != nil { return "", fmt.Errorf("failed to create temp directory: %w", err) } @@ -262,7 +262,7 @@ func (gi *GitInstaller) cloneRepository(info *GitPackageInfo) (string, error) { return tempDir, nil } -// findPackageRoot finds the root directory containing brain-package.yaml +// findPackageRoot finds the root directory containing haxen-package.yaml func (gi *GitInstaller) findPackageRoot(cloneDir string) (string, error) { var packageRoot string @@ -271,7 +271,7 @@ func (gi *GitInstaller) findPackageRoot(cloneDir string) (string, error) { return err } - if info.Name() == "brain-package.yaml" { + if info.Name() == "haxen-package.yaml" { packageRoot = filepath.Dir(path) return filepath.SkipDir // Found it, stop walking } @@ -284,7 +284,7 @@ func (gi *GitInstaller) findPackageRoot(cloneDir string) (string, error) { } if packageRoot == "" { - return "", fmt.Errorf("brain-package.yaml not found in the repository") + return "", fmt.Errorf("haxen-package.yaml not found in the repository") } // Also check for main.py @@ -296,10 +296,10 @@ func (gi *GitInstaller) findPackageRoot(cloneDir string) (string, error) { return packageRoot, nil } -// parsePackageMetadata parses the brain-package.yaml file (reuse from installer.go) +// parsePackageMetadata parses the haxen-package.yaml file (reuse from installer.go) func (gi *GitInstaller) parsePackageMetadata(packagePath string) (*PackageMetadata, error) { installer := &PackageInstaller{ - BrainHome: gi.BrainHome, + HaxenHome: gi.HaxenHome, Verbose: gi.Verbose, } return installer.parsePackageMetadata(packagePath) @@ -307,7 +307,7 @@ func (gi *GitInstaller) parsePackageMetadata(packagePath string) (*PackageMetada // updateRegistryWithGit updates the installation registry with Git source info func (gi *GitInstaller) updateRegistryWithGit(metadata *PackageMetadata, info *GitPackageInfo, sourcePath, destPath string) error { - registryPath := filepath.Join(gi.BrainHome, "installed.yaml") + registryPath := filepath.Join(gi.HaxenHome, "installed.yaml") // Load existing registry or create new one registry := &InstallationRegistry{ @@ -348,7 +348,7 @@ func (gi *GitInstaller) updateRegistryWithGit(metadata *PackageMetadata, info *G Port: nil, PID: nil, StartedAt: nil, - LogFile: filepath.Join(gi.BrainHome, "logs", metadata.Name+".log"), + LogFile: filepath.Join(gi.HaxenHome, "logs", metadata.Name+".log"), }, } diff --git a/control-plane/internal/packages/github.go b/control-plane/internal/packages/github.go index 4ff5c513..80c5c7d3 100644 --- a/control-plane/internal/packages/github.go +++ b/control-plane/internal/packages/github.go @@ -11,7 +11,7 @@ import ( "strings" "time" - "github.com/your-org/brain/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/logger" "gopkg.in/yaml.v3" ) @@ -26,7 +26,7 @@ type GitHubPackageInfo struct { // GitHubInstaller handles GitHub package installation type GitHubInstaller struct { - BrainHome string + HaxenHome string Verbose bool } @@ -161,7 +161,7 @@ func (gi *GitHubInstaller) InstallFromGitHub(githubURL string, force bool) error // 4. Use existing installer for the rest installer := &PackageInstaller{ - BrainHome: gi.BrainHome, + HaxenHome: gi.HaxenHome, Verbose: gi.Verbose, } @@ -171,7 +171,7 @@ func (gi *GitHubInstaller) InstallFromGitHub(githubURL string, force bool) error } // Install using existing flow - destPath := filepath.Join(gi.BrainHome, "packages", metadata.Name) + destPath := filepath.Join(gi.HaxenHome, "packages", metadata.Name) spinner = gi.newSpinner("Setting up environment") spinner.Start() @@ -201,7 +201,7 @@ func (gi *GitHubInstaller) InstallFromGitHub(githubURL string, force bool) error // Check for required environment variables installer.checkEnvironmentVariables(metadata) - logger.Logger.Info().Msgf("\n%s %s", Blue("→"), Bold(fmt.Sprintf("Run: brain run %s", metadata.Name))) + logger.Logger.Info().Msgf("\n%s %s", Blue("→"), Bold(fmt.Sprintf("Run: haxen run %s", metadata.Name))) return nil } @@ -209,7 +209,7 @@ func (gi *GitHubInstaller) InstallFromGitHub(githubURL string, force bool) error // downloadAndExtract downloads and extracts the GitHub archive func (gi *GitHubInstaller) downloadAndExtract(info *GitHubPackageInfo) (string, error) { // Create temporary directory - tempDir, err := os.MkdirTemp("", "brain-github-install-") + tempDir, err := os.MkdirTemp("", "haxen-github-install-") if err != nil { return "", fmt.Errorf("failed to create temp directory: %w", err) } @@ -308,7 +308,7 @@ func (gi *GitHubInstaller) extractZip(src, dest string) error { return nil } -// findPackageRoot finds the root directory containing brain-package.yaml +// findPackageRoot finds the root directory containing haxen-package.yaml func (gi *GitHubInstaller) findPackageRoot(extractDir string) (string, error) { var packageRoot string @@ -317,7 +317,7 @@ func (gi *GitHubInstaller) findPackageRoot(extractDir string) (string, error) { return err } - if info.Name() == "brain-package.yaml" { + if info.Name() == "haxen-package.yaml" { packageRoot = filepath.Dir(path) return filepath.SkipDir // Found it, stop walking } @@ -330,7 +330,7 @@ func (gi *GitHubInstaller) findPackageRoot(extractDir string) (string, error) { } if packageRoot == "" { - return "", fmt.Errorf("brain-package.yaml not found in the repository") + return "", fmt.Errorf("haxen-package.yaml not found in the repository") } // Also check for main.py @@ -342,10 +342,10 @@ func (gi *GitHubInstaller) findPackageRoot(extractDir string) (string, error) { return packageRoot, nil } -// parsePackageMetadata parses the brain-package.yaml file (reuse from installer.go) +// parsePackageMetadata parses the haxen-package.yaml file (reuse from installer.go) func (gi *GitHubInstaller) parsePackageMetadata(packagePath string) (*PackageMetadata, error) { installer := &PackageInstaller{ - BrainHome: gi.BrainHome, + HaxenHome: gi.HaxenHome, Verbose: gi.Verbose, } return installer.parsePackageMetadata(packagePath) @@ -353,7 +353,7 @@ func (gi *GitHubInstaller) parsePackageMetadata(packagePath string) (*PackageMet // updateRegistryWithGitHub updates the installation registry with GitHub source info func (gi *GitHubInstaller) updateRegistryWithGitHub(metadata *PackageMetadata, info *GitHubPackageInfo, sourcePath, destPath string) error { - registryPath := filepath.Join(gi.BrainHome, "installed.yaml") + registryPath := filepath.Join(gi.HaxenHome, "installed.yaml") // Load existing registry or create new one registry := &InstallationRegistry{ @@ -378,7 +378,7 @@ func (gi *GitHubInstaller) updateRegistryWithGitHub(metadata *PackageMetadata, i Port: nil, PID: nil, StartedAt: nil, - LogFile: filepath.Join(gi.BrainHome, "logs", metadata.Name+".log"), + LogFile: filepath.Join(gi.HaxenHome, "logs", metadata.Name+".log"), }, } diff --git a/control-plane/internal/packages/installer.go b/control-plane/internal/packages/installer.go index 9da373fa..394ffcdf 100644 --- a/control-plane/internal/packages/installer.go +++ b/control-plane/internal/packages/installer.go @@ -29,7 +29,7 @@ type UserEnvironmentConfig struct { Optional []UserEnvironmentVar `yaml:"optional"` } -// PackageMetadata represents the structure of brain-package.yaml +// PackageMetadata represents the structure of haxen-package.yaml type PackageMetadata struct { Name string `yaml:"name"` Version string `yaml:"version"` @@ -96,7 +96,7 @@ type RuntimeInfo struct { // PackageInstaller handles package installation type PackageInstaller struct { - BrainHome string + HaxenHome string Verbose bool } @@ -210,7 +210,7 @@ func (pi *PackageInstaller) InstallPackage(sourcePath string, force bool) error } // 3. Copy package to global location - destPath := filepath.Join(pi.BrainHome, "packages", metadata.Name) + destPath := filepath.Join(pi.HaxenHome, "packages", metadata.Name) spinner = pi.newSpinner("Setting up environment") spinner.Start() if err := pi.copyPackage(sourcePath, destPath); err != nil { @@ -239,7 +239,7 @@ func (pi *PackageInstaller) InstallPackage(sourcePath string, force bool) error // 6. Check for required environment variables and provide guidance pi.checkEnvironmentVariables(metadata) - fmt.Printf("\n%s %s\n", Blue("→"), Bold(fmt.Sprintf("Run: brain run %s", metadata.Name))) + fmt.Printf("\n%s %s\n", Blue("→"), Bold(fmt.Sprintf("Run: haxen run %s", metadata.Name))) return nil } @@ -261,7 +261,7 @@ func (pi *PackageInstaller) checkEnvironmentVariables(metadata *PackageMetadata) if len(missingRequired) > 0 { fmt.Printf("\n%s %s\n", Yellow("⚠"), Bold("Missing required environment variables:")) for _, envVar := range missingRequired { - fmt.Printf(" %s\n", Cyan(fmt.Sprintf("brain config %s --set %s=your-value-here", metadata.Name, envVar.Name))) + fmt.Printf(" %s\n", Cyan(fmt.Sprintf("haxen config %s --set %s=your-value-here", metadata.Name, envVar.Name))) } } @@ -281,7 +281,7 @@ func (pi *PackageInstaller) checkEnvironmentVariables(metadata *PackageMetadata) // PackageUninstaller handles package uninstallation type PackageUninstaller struct { - BrainHome string + HaxenHome string Force bool } @@ -357,7 +357,7 @@ func (pu *PackageUninstaller) stopAgentNode(agentNode *InstalledPackage) error { // loadRegistry loads the installation registry func (pu *PackageUninstaller) loadRegistry() (*InstallationRegistry, error) { - registryPath := filepath.Join(pu.BrainHome, "installed.yaml") + registryPath := filepath.Join(pu.HaxenHome, "installed.yaml") registry := &InstallationRegistry{ Installed: make(map[string]InstalledPackage), @@ -374,7 +374,7 @@ func (pu *PackageUninstaller) loadRegistry() (*InstallationRegistry, error) { // saveRegistry saves the installation registry func (pu *PackageUninstaller) saveRegistry(registry *InstallationRegistry) error { - registryPath := filepath.Join(pu.BrainHome, "installed.yaml") + registryPath := filepath.Join(pu.HaxenHome, "installed.yaml") data, err := yaml.Marshal(registry) if err != nil { @@ -390,10 +390,10 @@ func (pu *PackageUninstaller) saveRegistry(registry *InstallationRegistry) error // validatePackage checks if the package has required files func (pi *PackageInstaller) validatePackage(sourcePath string) error { - // Check if brain-package.yaml exists - packageYamlPath := filepath.Join(sourcePath, "brain-package.yaml") + // Check if haxen-package.yaml exists + packageYamlPath := filepath.Join(sourcePath, "haxen-package.yaml") if _, err := os.Stat(packageYamlPath); os.IsNotExist(err) { - return fmt.Errorf("brain-package.yaml not found in %s", sourcePath) + return fmt.Errorf("haxen-package.yaml not found in %s", sourcePath) } // Check if main.py exists @@ -405,26 +405,26 @@ func (pi *PackageInstaller) validatePackage(sourcePath string) error { return nil } -// parsePackageMetadata parses the brain-package.yaml file +// parsePackageMetadata parses the haxen-package.yaml file func (pi *PackageInstaller) parsePackageMetadata(sourcePath string) (*PackageMetadata, error) { - packageYamlPath := filepath.Join(sourcePath, "brain-package.yaml") + packageYamlPath := filepath.Join(sourcePath, "haxen-package.yaml") data, err := os.ReadFile(packageYamlPath) if err != nil { - return nil, fmt.Errorf("failed to read brain-package.yaml: %w", err) + return nil, fmt.Errorf("failed to read haxen-package.yaml: %w", err) } var metadata PackageMetadata if err := yaml.Unmarshal(data, &metadata); err != nil { - return nil, fmt.Errorf("failed to parse brain-package.yaml: %w", err) + return nil, fmt.Errorf("failed to parse haxen-package.yaml: %w", err) } // Validate required fields if metadata.Name == "" { - return nil, fmt.Errorf("package name is required in brain-package.yaml") + return nil, fmt.Errorf("package name is required in haxen-package.yaml") } if metadata.Version == "" { - return nil, fmt.Errorf("package version is required in brain-package.yaml") + return nil, fmt.Errorf("package version is required in haxen-package.yaml") } if metadata.Main == "" { metadata.Main = "main.py" // Default @@ -435,7 +435,7 @@ func (pi *PackageInstaller) parsePackageMetadata(sourcePath string) (*PackageMet // isPackageInstalled checks if a package is already installed func (pi *PackageInstaller) isPackageInstalled(packageName string) bool { - registryPath := filepath.Join(pi.BrainHome, "installed.yaml") + registryPath := filepath.Join(pi.HaxenHome, "installed.yaml") registry := &InstallationRegistry{ Installed: make(map[string]InstalledPackage), } @@ -541,7 +541,7 @@ func (pi *PackageInstaller) installDependencies(packagePath string, metadata *Pa } } - // Install dependencies from brain-package.yaml + // Install dependencies from haxen-package.yaml if len(metadata.Dependencies.Python) > 0 { for _, dep := range metadata.Dependencies.Python { cmd = exec.Command(pipPath, "install", dep) @@ -570,7 +570,7 @@ func (pi *PackageInstaller) hasRequirementsFile(packagePath string) bool { // updateRegistry updates the installation registry with the new package func (pi *PackageInstaller) updateRegistry(metadata *PackageMetadata, sourcePath, destPath string) error { - registryPath := filepath.Join(pi.BrainHome, "installed.yaml") + registryPath := filepath.Join(pi.HaxenHome, "installed.yaml") // Load existing registry or create new one registry := &InstallationRegistry{ @@ -582,7 +582,7 @@ func (pi *PackageInstaller) updateRegistry(metadata *PackageMetadata, sourcePath } // Ensure logs directory exists before setting LogFile path - logsDir := filepath.Join(pi.BrainHome, "logs") + logsDir := filepath.Join(pi.HaxenHome, "logs") if err := os.MkdirAll(logsDir, 0755); err != nil { return fmt.Errorf("failed to create logs directory: %w", err) } @@ -602,7 +602,7 @@ func (pi *PackageInstaller) updateRegistry(metadata *PackageMetadata, sourcePath Port: nil, PID: nil, StartedAt: nil, - LogFile: filepath.Join(pi.BrainHome, "logs", metadata.Name+".log"), + LogFile: filepath.Join(pi.HaxenHome, "logs", metadata.Name+".log"), }, } diff --git a/control-plane/internal/packages/runner.go b/control-plane/internal/packages/runner.go index d0546e69..193a2d94 100644 --- a/control-plane/internal/packages/runner.go +++ b/control-plane/internal/packages/runner.go @@ -16,7 +16,7 @@ import ( // AgentNodeRunner handles running agent nodes type AgentNodeRunner struct { - BrainHome string + HaxenHome string Port int Detach bool } @@ -67,7 +67,7 @@ func (ar *AgentNodeRunner) RunAgentNode(agentNodeName string) error { return fmt.Errorf("agent node failed to start: %w", err) } - fmt.Printf("🧠 Agent node registered with Brain Server\n") + fmt.Printf("🧠 Agent node registered with Haxen Server\n") // 6. Update registry with runtime info if err := ar.updateRuntimeInfo(agentNodeName, port, cmd.Process.Pid); err != nil { @@ -80,8 +80,8 @@ func (ar *AgentNodeRunner) RunAgentNode(agentNodeName string) error { } fmt.Printf("\n💡 Agent node running in background (PID: %d)\n", cmd.Process.Pid) - fmt.Printf("💡 View logs: brain logs %s\n", agentNodeName) - fmt.Printf("💡 Stop agent node: brain stop %s\n", agentNodeName) + fmt.Printf("💡 View logs: haxen logs %s\n", agentNodeName) + fmt.Printf("💡 Stop agent node: haxen stop %s\n", agentNodeName) return nil } @@ -111,7 +111,7 @@ func (ar *AgentNodeRunner) startAgentNodeProcess(agentNode InstalledPackage, por // Prepare environment variables env := os.Environ() env = append(env, fmt.Sprintf("PORT=%d", port)) - env = append(env, "BRAIN_SERVER_URL=http://localhost:8080") + env = append(env, "HAXEN_SERVER_URL=http://localhost:8080") // Load environment variables from package .env file if envVars, err := ar.loadPackageEnvFile(agentNode.Path); err == nil { @@ -243,7 +243,7 @@ func (ar *AgentNodeRunner) displayCapabilities(agentNode InstalledPackage, port // updateRuntimeInfo updates the registry with runtime information func (ar *AgentNodeRunner) updateRuntimeInfo(agentNodeName string, port, pid int) error { - registryPath := filepath.Join(ar.BrainHome, "installed.yaml") + registryPath := filepath.Join(ar.HaxenHome, "installed.yaml") // Load registry registry := &InstallationRegistry{} @@ -272,7 +272,7 @@ func (ar *AgentNodeRunner) updateRuntimeInfo(agentNodeName string, port, pid int // loadRegistry loads the installation registry func (ar *AgentNodeRunner) loadRegistry() (*InstallationRegistry, error) { - registryPath := filepath.Join(ar.BrainHome, "installed.yaml") + registryPath := filepath.Join(ar.HaxenHome, "installed.yaml") registry := &InstallationRegistry{ Installed: make(map[string]InstalledPackage), diff --git a/control-plane/internal/server/package_sync.go b/control-plane/internal/server/package_sync.go index c2125f3a..f05a577e 100644 --- a/control-plane/internal/server/package_sync.go +++ b/control-plane/internal/server/package_sync.go @@ -1,8 +1,8 @@ package server import ( - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/pkg/types" "context" "encoding/json" "fmt" @@ -47,9 +47,9 @@ type InstalledPackage struct { } // SyncPackagesFromRegistry ensures all packages in installed.yaml are present in the database. -func SyncPackagesFromRegistry(brainHome string, storageProvider packageStorage) error { +func SyncPackagesFromRegistry(haxenHome string, storageProvider packageStorage) error { ctx := context.Background() - registryPath := filepath.Join(brainHome, "installed.yaml") + registryPath := filepath.Join(haxenHome, "installed.yaml") data, err := os.ReadFile(registryPath) if err != nil { return nil // No registry, nothing to sync @@ -64,8 +64,8 @@ func SyncPackagesFromRegistry(brainHome string, storageProvider packageStorage) if err == nil { continue // Already present } - // Load brain-package.yaml - packageYamlPath := filepath.Join(pkg.Path, "brain-package.yaml") + // Load haxen-package.yaml + packageYamlPath := filepath.Join(pkg.Path, "haxen-package.yaml") packageYamlData, err := os.ReadFile(packageYamlPath) if err != nil { continue // Skip if missing @@ -95,13 +95,13 @@ func SyncPackagesFromRegistry(brainHome string, storageProvider packageStorage) } // StartPackageRegistryWatcher watches the installed.yaml registry and keeps storage in sync. -func StartPackageRegistryWatcher(parentCtx context.Context, brainHome string, storageProvider packageStorage) (context.CancelFunc, error) { +func StartPackageRegistryWatcher(parentCtx context.Context, haxenHome string, storageProvider packageStorage) (context.CancelFunc, error) { watcher, err := fsnotify.NewWatcher() if err != nil { return nil, fmt.Errorf("failed to create registry watcher: %w", err) } - registryDir := brainHome + registryDir := haxenHome if err := watcher.Add(registryDir); err != nil { watcher.Close() return nil, fmt.Errorf("failed to watch registry directory %s: %w", registryDir, err) @@ -122,7 +122,7 @@ func StartPackageRegistryWatcher(parentCtx context.Context, brainHome string, st go func() { defer watcher.Close() defer close(syncCh) - registryFile := filepath.Join(brainHome, "installed.yaml") + registryFile := filepath.Join(haxenHome, "installed.yaml") for { select { case event, ok := <-watcher.Events: @@ -162,7 +162,7 @@ func StartPackageRegistryWatcher(parentCtx context.Context, brainHome string, st return } time.Sleep(250 * time.Millisecond) - if err := SyncPackagesFromRegistry(brainHome, storageProvider); err != nil { + if err := SyncPackagesFromRegistry(haxenHome, storageProvider); err != nil { logger.Logger.Error().Err(err).Msg("failed to sync packages from registry") } else { logger.Logger.Debug().Msg("registry sync completed") diff --git a/control-plane/internal/server/package_sync_test.go b/control-plane/internal/server/package_sync_test.go index 8c161b2d..e446190e 100644 --- a/control-plane/internal/server/package_sync_test.go +++ b/control-plane/internal/server/package_sync_test.go @@ -6,7 +6,7 @@ import ( "testing" "time" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/stretchr/testify/require" ) @@ -14,8 +14,8 @@ import ( func TestSyncPackagesFromRegistryStoresMissingPackages(t *testing.T) { t.Parallel() - brainHome := t.TempDir() - pkgDir := filepath.Join(brainHome, "example-agent") + haxenHome := t.TempDir() + pkgDir := filepath.Join(haxenHome, "example-agent") require.NoError(t, os.MkdirAll(pkgDir, 0o755)) installed := `installed: @@ -27,17 +27,17 @@ func TestSyncPackagesFromRegistryStoresMissingPackages(t *testing.T) { source: local status: installed ` - require.NoError(t, os.WriteFile(filepath.Join(brainHome, "installed.yaml"), []byte(installed), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(haxenHome, "installed.yaml"), []byte(installed), 0o644)) packageYAML := `name: Example Agent version: 1.0.0 schema: type: object ` - require.NoError(t, os.WriteFile(filepath.Join(pkgDir, "brain-package.yaml"), []byte(packageYAML), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(pkgDir, "haxen-package.yaml"), []byte(packageYAML), 0o644)) storage := newStubPackageStorage() - require.NoError(t, SyncPackagesFromRegistry(brainHome, storage)) + require.NoError(t, SyncPackagesFromRegistry(haxenHome, storage)) pkg, ok := storage.packages["example-agent"] require.True(t, ok) @@ -48,20 +48,20 @@ schema: func TestSyncPackagesSkipsExistingEntries(t *testing.T) { t.Parallel() - brainHome := t.TempDir() + haxenHome := t.TempDir() installed := `installed: existing-agent: name: Existing version: 0.1.0 description: already present - path: ` + brainHome + ` + path: ` + haxenHome + ` ` - require.NoError(t, os.WriteFile(filepath.Join(brainHome, "installed.yaml"), []byte(installed), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(haxenHome, "installed.yaml"), []byte(installed), 0o644)) storage := newStubPackageStorage() storage.packages["existing-agent"] = &types.AgentPackage{ID: "existing-agent", Name: "Existing", InstalledAt: time.Now()} - require.NoError(t, SyncPackagesFromRegistry(brainHome, storage)) + require.NoError(t, SyncPackagesFromRegistry(haxenHome, storage)) require.Len(t, storage.packages, 1) } diff --git a/control-plane/internal/server/server.go b/control-plane/internal/server/server.go index 3834520a..4717b70f 100644 --- a/control-plane/internal/server/server.go +++ b/control-plane/internal/server/server.go @@ -1,22 +1,22 @@ package server import ( - "github.com/your-org/brain/control-plane/internal/config" - "github.com/your-org/brain/control-plane/internal/core/interfaces" - coreservices "github.com/your-org/brain/control-plane/internal/core/services" // Core services - "github.com/your-org/brain/control-plane/internal/events" // Event system - "github.com/your-org/brain/control-plane/internal/handlers" // Agent handlers - "github.com/your-org/brain/control-plane/internal/handlers/ui" // UI handlers - "github.com/your-org/brain/control-plane/internal/infrastructure/communication" - "github.com/your-org/brain/control-plane/internal/infrastructure/process" - infrastorage "github.com/your-org/brain/control-plane/internal/infrastructure/storage" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/internal/services" // Services - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/internal/utils" - "github.com/your-org/brain/control-plane/pkg/adminpb" - "github.com/your-org/brain/control-plane/pkg/types" - client "github.com/your-org/brain/control-plane/web/client" + "github.com/your-org/haxen/control-plane/internal/config" + "github.com/your-org/haxen/control-plane/internal/core/interfaces" + coreservices "github.com/your-org/haxen/control-plane/internal/core/services" // Core services + "github.com/your-org/haxen/control-plane/internal/events" // Event system + "github.com/your-org/haxen/control-plane/internal/handlers" // Agent handlers + "github.com/your-org/haxen/control-plane/internal/handlers/ui" // UI handlers + "github.com/your-org/haxen/control-plane/internal/infrastructure/communication" + "github.com/your-org/haxen/control-plane/internal/infrastructure/process" + infrastorage "github.com/your-org/haxen/control-plane/internal/infrastructure/storage" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/services" // Services + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/internal/utils" + "github.com/your-org/haxen/control-plane/pkg/adminpb" + "github.com/your-org/haxen/control-plane/pkg/types" + client "github.com/your-org/haxen/control-plane/web/client" "context" "crypto/sha256" "encoding/hex" @@ -38,8 +38,8 @@ import ( "google.golang.org/grpc/status" ) -// BrainServer represents the core Brain orchestration service. -type BrainServer struct { +// HaxenServer represents the core Haxen orchestration service. +type HaxenServer struct { adminpb.UnimplementedAdminReasonerServiceServer storage storage.StorageProvider cache storage.CacheProvider @@ -59,7 +59,7 @@ type BrainServer struct { didService *services.DIDService vcService *services.VCService didRegistry *services.DIDRegistry - brainHome string + haxenHome string // Cleanup service cleanupService *handlers.ExecutionCleanupService payloadStore services.PayloadStore @@ -70,16 +70,16 @@ type BrainServer struct { webhookDispatcher services.WebhookDispatcher } -// NewBrainServer creates a new instance of the BrainServer. -func NewBrainServer(cfg *config.Config) (*BrainServer, error) { - // Define brainHome at the very top - brainHome := os.Getenv("BRAIN_HOME") - if brainHome == "" { +// NewHaxenServer creates a new instance of the HaxenServer. +func NewHaxenServer(cfg *config.Config) (*HaxenServer, error) { + // Define haxenHome at the very top + haxenHome := os.Getenv("HAXEN_HOME") + if haxenHome == "" { homeDir, err := os.UserHomeDir() if err != nil { return nil, err } - brainHome = filepath.Join(homeDir, ".brain") + haxenHome = filepath.Join(homeDir, ".haxen") } dirs, err := utils.EnsureDataDirectories() @@ -96,20 +96,20 @@ func NewBrainServer(cfg *config.Config) (*BrainServer, error) { Router := gin.Default() // Sync installed.yaml to database for package visibility - _ = SyncPackagesFromRegistry(brainHome, storageProvider) + _ = SyncPackagesFromRegistry(haxenHome, storageProvider) // Initialize agent client for communication with agent nodes agentClient := communication.NewHTTPAgentClient(storageProvider, 5*time.Second) // Create infrastructure components for AgentService fileSystem := infrastorage.NewFileSystemAdapter() - registryPath := filepath.Join(brainHome, "installed.json") + registryPath := filepath.Join(haxenHome, "installed.json") registryStorage := infrastorage.NewLocalRegistryStorage(fileSystem, registryPath) processManager := process.NewProcessManager() portManager := process.NewPortManager() // Create AgentService - agentService := coreservices.NewAgentService(processManager, portManager, registryStorage, agentClient, brainHome) + agentService := coreservices.NewAgentService(processManager, portManager, registryStorage, agentClient, haxenHome) // Initialize StatusManager for unified status management statusManagerConfig := services.StatusManagerConfig{ @@ -189,25 +189,25 @@ func NewBrainServer(cfg *config.Config) (*BrainServer, error) { return nil, fmt.Errorf("failed to initialize VC service: %w", err) } - // Generate brain server ID based on brain home directory - brainServerID := generateBrainServerID(brainHome) + // Generate haxen server ID based on haxen home directory + haxenServerID := generateHaxenServerID(haxenHome) - // Initialize brain server DID with dynamic ID - fmt.Printf("🧠 Initializing brain server DID (ID: %s)...\n", brainServerID) - if err := didService.Initialize(brainServerID); err != nil { - return nil, fmt.Errorf("failed to initialize brain server DID: %w", err) + // Initialize haxen server DID with dynamic ID + fmt.Printf("🧠 Initializing haxen server DID (ID: %s)...\n", haxenServerID) + if err := didService.Initialize(haxenServerID); err != nil { + return nil, fmt.Errorf("failed to initialize haxen server DID: %w", err) } - // Validate that brain server DID was successfully created - registry, err := didService.GetRegistry(brainServerID) + // Validate that haxen server DID was successfully created + registry, err := didService.GetRegistry(haxenServerID) if err != nil { - return nil, fmt.Errorf("failed to validate brain server DID creation: %w", err) + return nil, fmt.Errorf("failed to validate haxen server DID creation: %w", err) } if registry == nil || registry.RootDID == "" { - return nil, fmt.Errorf("brain server DID validation failed: registry or root DID is empty") + return nil, fmt.Errorf("haxen server DID validation failed: registry or root DID is empty") } - fmt.Printf("✅ Brain server DID created successfully: %s\n", registry.RootDID) + fmt.Printf("✅ Haxen server DID created successfully: %s\n", registry.RootDID) // Backfill existing nodes with DIDs fmt.Println("🔄 Starting DID backfill for existing nodes...") @@ -224,28 +224,28 @@ func NewBrainServer(cfg *config.Config) (*BrainServer, error) { payloadStore := services.NewFilePayloadStore(dirs.PayloadsDir) webhookDispatcher := services.NewWebhookDispatcher(storageProvider, services.WebhookDispatcherConfig{ - Timeout: cfg.Brain.ExecutionQueue.WebhookTimeout, - MaxAttempts: cfg.Brain.ExecutionQueue.WebhookMaxAttempts, - RetryBackoff: cfg.Brain.ExecutionQueue.WebhookRetryBackoff, - MaxRetryBackoff: cfg.Brain.ExecutionQueue.WebhookMaxRetryBackoff, + Timeout: cfg.Haxen.ExecutionQueue.WebhookTimeout, + MaxAttempts: cfg.Haxen.ExecutionQueue.WebhookMaxAttempts, + RetryBackoff: cfg.Haxen.ExecutionQueue.WebhookRetryBackoff, + MaxRetryBackoff: cfg.Haxen.ExecutionQueue.WebhookMaxRetryBackoff, }) if err := webhookDispatcher.Start(context.Background()); err != nil { logger.Logger.Warn().Err(err).Msg("failed to start webhook dispatcher") } // Initialize execution cleanup service - cleanupService := handlers.NewExecutionCleanupService(storageProvider, cfg.Brain.ExecutionCleanup) + cleanupService := handlers.NewExecutionCleanupService(storageProvider, cfg.Haxen.ExecutionCleanup) - adminPort := cfg.Brain.Port + 100 - if envPort := os.Getenv("BRAIN_ADMIN_GRPC_PORT"); envPort != "" { + adminPort := cfg.Haxen.Port + 100 + if envPort := os.Getenv("HAXEN_ADMIN_GRPC_PORT"); envPort != "" { if parsedPort, parseErr := strconv.Atoi(envPort); parseErr == nil { adminPort = parsedPort } else { - logger.Logger.Warn().Err(parseErr).Str("value", envPort).Msg("invalid BRAIN_ADMIN_GRPC_PORT, using default offset") + logger.Logger.Warn().Err(parseErr).Str("value", envPort).Msg("invalid HAXEN_ADMIN_GRPC_PORT, using default offset") } } - return &BrainServer{ + return &HaxenServer{ storage: storageProvider, cache: cacheProvider, Router: Router, @@ -261,7 +261,7 @@ func NewBrainServer(cfg *config.Config) (*BrainServer, error) { didService: didService, vcService: vcService, didRegistry: didRegistry, - brainHome: brainHome, + haxenHome: haxenHome, cleanupService: cleanupService, payloadStore: payloadStore, webhookDispatcher: webhookDispatcher, @@ -270,8 +270,8 @@ func NewBrainServer(cfg *config.Config) (*BrainServer, error) { }, nil } -// Start initializes and starts the BrainServer. -func (s *BrainServer) Start() error { +// Start initializes and starts the HaxenServer. +func (s *HaxenServer) Start() error { // Setup routes s.setupRoutes() @@ -299,7 +299,7 @@ func (s *BrainServer) Start() error { events.StartNodeHeartbeat(30 * time.Second) if s.registryWatcherCancel == nil { - cancel, err := StartPackageRegistryWatcher(context.Background(), s.brainHome, s.storage) + cancel, err := StartPackageRegistryWatcher(context.Background(), s.haxenHome, s.storage) if err != nil { logger.Logger.Error().Err(err).Msg("failed to start package registry watcher") } else { @@ -313,10 +313,10 @@ func (s *BrainServer) Start() error { // TODO: Implement WebSocket, gRPC // Start HTTP server - return s.Router.Run(":" + strconv.Itoa(s.config.Brain.Port)) + return s.Router.Run(":" + strconv.Itoa(s.config.Haxen.Port)) } -func (s *BrainServer) startAdminGRPCServer() error { +func (s *HaxenServer) startAdminGRPCServer() error { if s.adminGRPCServer != nil { return nil } @@ -341,7 +341,7 @@ func (s *BrainServer) startAdminGRPCServer() error { } // ListReasoners implements the admin gRPC surface for listing registered reasoners. -func (s *BrainServer) ListReasoners(ctx context.Context, _ *adminpb.ListReasonersRequest) (*adminpb.ListReasonersResponse, error) { +func (s *HaxenServer) ListReasoners(ctx context.Context, _ *adminpb.ListReasonersRequest) (*adminpb.ListReasonersResponse, error) { nodes, err := s.storage.ListAgents(ctx, types.AgentFilters{}) if err != nil { return nil, status.Errorf(codes.Internal, "failed to list agent nodes: %v", err) @@ -368,8 +368,8 @@ func (s *BrainServer) ListReasoners(ctx context.Context, _ *adminpb.ListReasoner return resp, nil } -// Stop gracefully shuts down the BrainServer. -func (s *BrainServer) Stop() error { +// Stop gracefully shuts down the HaxenServer. +func (s *HaxenServer) Stop() error { if s.adminGRPCServer != nil { s.adminGRPCServer.GracefulStop() } @@ -411,7 +411,7 @@ func (s *BrainServer) Stop() error { } // unregisterAgentFromMonitoring removes an agent from health monitoring -func (s *BrainServer) unregisterAgentFromMonitoring(c *gin.Context) { +func (s *HaxenServer) unregisterAgentFromMonitoring(c *gin.Context) { nodeID := c.Param("node_id") if nodeID == "" { c.JSON(http.StatusBadRequest, gin.H{"error": "node_id is required"}) @@ -430,7 +430,7 @@ func (s *BrainServer) unregisterAgentFromMonitoring(c *gin.Context) { } // healthCheckHandler provides comprehensive health check for container orchestration -func (s *BrainServer) healthCheckHandler(c *gin.Context) { +func (s *HaxenServer) healthCheckHandler(c *gin.Context) { ctx, cancel := context.WithTimeout(c.Request.Context(), 10*time.Second) defer cancel() @@ -484,7 +484,7 @@ func (s *BrainServer) healthCheckHandler(c *gin.Context) { } // checkStorageHealth performs storage-specific health checks -func (s *BrainServer) checkStorageHealth(ctx context.Context) gin.H { +func (s *HaxenServer) checkStorageHealth(ctx context.Context) gin.H { if s.storageHealthOverride != nil { return s.storageHealthOverride(ctx) } @@ -507,7 +507,7 @@ func (s *BrainServer) checkStorageHealth(ctx context.Context) gin.H { } // checkCacheHealth performs cache-specific health checks -func (s *BrainServer) checkCacheHealth(ctx context.Context) gin.H { +func (s *HaxenServer) checkCacheHealth(ctx context.Context) gin.H { if s.cacheHealthOverride != nil { return s.cacheHealthOverride(ctx) } @@ -547,7 +547,7 @@ func (s *BrainServer) checkCacheHealth(ctx context.Context) gin.H { } } -func (s *BrainServer) setupRoutes() { +func (s *HaxenServer) setupRoutes() { // Configure CORS from configuration corsConfig := cors.Config{ AllowOrigins: s.config.API.CORS.AllowedOrigins, @@ -613,7 +613,7 @@ func (s *BrainServer) setupRoutes() { // Get the executable path and find UI dist relative to it execPath, err := os.Executable() if err != nil { - distPath = filepath.Join("apps", "platform", "brain", "web", "client", "dist") + distPath = filepath.Join("apps", "platform", "haxen", "web", "client", "dist") if _, statErr := os.Stat(distPath); os.IsNotExist(statErr) { distPath = filepath.Join("web", "client", "dist") } @@ -622,14 +622,14 @@ func (s *BrainServer) setupRoutes() { // Look for web/client/dist relative to the executable directory distPath = filepath.Join(execDir, "web", "client", "dist") - // If that doesn't exist, try going up one level (if binary is in apps/platform/brain/) + // If that doesn't exist, try going up one level (if binary is in apps/platform/haxen/) if _, err := os.Stat(distPath); os.IsNotExist(err) { - distPath = filepath.Join(filepath.Dir(execDir), "apps", "platform", "brain", "web", "client", "dist") + distPath = filepath.Join(filepath.Dir(execDir), "apps", "platform", "haxen", "web", "client", "dist") } // Final fallback to current working directory if _, err := os.Stat(distPath); os.IsNotExist(err) { - altPath := filepath.Join("apps", "platform", "brain", "web", "client", "dist") + altPath := filepath.Join("apps", "platform", "haxen", "web", "client", "dist") if _, altErr := os.Stat(altPath); altErr == nil { distPath = altPath } else { @@ -684,7 +684,7 @@ func (s *BrainServer) setupRoutes() { agents.POST("/:agentId/config", configHandler.SetConfigHandler) // Environment file endpoints - envHandler := ui.NewEnvHandler(s.storage, s.agentService, s.brainHome) + envHandler := ui.NewEnvHandler(s.storage, s.agentService, s.haxenHome) agents.GET("/:agentId/env", envHandler.GetEnvHandler) agents.PUT("/:agentId/env", envHandler.PutEnvHandler) agents.PATCH("/:agentId/env", envHandler.PatchEnvHandler) @@ -901,23 +901,23 @@ func (s *BrainServer) setupRoutes() { // Register service-backed DID routes didHandlers.RegisterRoutes(agentAPI) - // Add brain server DID endpoint - agentAPI.GET("/did/brain-server", func(c *gin.Context) { - // Get brain server ID dynamically - brainServerID, err := s.didService.GetBrainServerID() + // Add haxen server DID endpoint + agentAPI.GET("/did/haxen-server", func(c *gin.Context) { + // Get haxen server ID dynamically + haxenServerID, err := s.didService.GetHaxenServerID() if err != nil { c.JSON(http.StatusInternalServerError, gin.H{ - "error": "Failed to get brain server ID", - "details": fmt.Sprintf("Brain server ID error: %v", err), + "error": "Failed to get haxen server ID", + "details": fmt.Sprintf("Haxen server ID error: %v", err), }) return } - // Get the actual brain server DID from the registry - registry, err := s.didService.GetRegistry(brainServerID) + // Get the actual haxen server DID from the registry + registry, err := s.didService.GetRegistry(haxenServerID) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{ - "error": "Failed to get brain server DID", + "error": "Failed to get haxen server DID", "details": fmt.Sprintf("Registry error: %v", err), }) return @@ -925,24 +925,24 @@ func (s *BrainServer) setupRoutes() { if registry == nil { c.JSON(http.StatusNotFound, gin.H{ - "error": "Brain server DID not found", - "details": "No DID registry exists for brain server 'default'. The DID system may not be properly initialized.", + "error": "Haxen server DID not found", + "details": "No DID registry exists for haxen server 'default'. The DID system may not be properly initialized.", }) return } if registry.RootDID == "" { c.JSON(http.StatusInternalServerError, gin.H{ - "error": "Brain server DID is empty", + "error": "Haxen server DID is empty", "details": "Registry exists but root DID is empty. The DID system may be corrupted.", }) return } c.JSON(http.StatusOK, gin.H{ - "brain_server_id": "default", - "brain_server_did": registry.RootDID, - "message": "Brain server DID retrieved successfully", + "haxen_server_id": "default", + "haxen_server_did": registry.RootDID, + "message": "Haxen server DID retrieved successfully", }) }) } else { @@ -995,7 +995,7 @@ func (s *BrainServer) setupRoutes() { // Get the executable path and find UI dist relative to it execPath, err := os.Executable() if err != nil { - distPath = filepath.Join("apps", "platform", "brain", "web", "client", "dist") + distPath = filepath.Join("apps", "platform", "haxen", "web", "client", "dist") if _, statErr := os.Stat(distPath); os.IsNotExist(statErr) { distPath = filepath.Join("web", "client", "dist") } @@ -1004,14 +1004,14 @@ func (s *BrainServer) setupRoutes() { // Look for web/client/dist relative to the executable directory distPath = filepath.Join(execDir, "web", "client", "dist") - // If that doesn't exist, try going up one level (if binary is in apps/platform/brain/) + // If that doesn't exist, try going up one level (if binary is in apps/platform/haxen/) if _, err := os.Stat(distPath); os.IsNotExist(err) { - distPath = filepath.Join(filepath.Dir(execDir), "apps", "platform", "brain", "web", "client", "dist") + distPath = filepath.Join(filepath.Dir(execDir), "apps", "platform", "haxen", "web", "client", "dist") } // Final fallback to current working directory if _, err := os.Stat(distPath); os.IsNotExist(err) { - altPath := filepath.Join("apps", "platform", "brain", "web", "client", "dist") + altPath := filepath.Join("apps", "platform", "haxen", "web", "client", "dist") if _, altErr := os.Stat(altPath); altErr == nil { distPath = altPath } else { @@ -1029,22 +1029,22 @@ func (s *BrainServer) setupRoutes() { } } -// generateBrainServerID creates a deterministic brain server ID based on the brain home directory. -// This ensures each brain instance has a unique ID while being deterministic for the same installation. -func generateBrainServerID(brainHome string) string { - // Use the absolute path of brain home to generate a deterministic ID - absPath, err := filepath.Abs(brainHome) +// generateHaxenServerID creates a deterministic haxen server ID based on the haxen home directory. +// This ensures each haxen instance has a unique ID while being deterministic for the same installation. +func generateHaxenServerID(haxenHome string) string { + // Use the absolute path of haxen home to generate a deterministic ID + absPath, err := filepath.Abs(haxenHome) if err != nil { // Fallback to the original path if absolute path fails - absPath = brainHome + absPath = haxenHome } - // Create a hash of the brain home path to generate a unique but deterministic ID + // Create a hash of the haxen home path to generate a unique but deterministic ID hash := sha256.Sum256([]byte(absPath)) - // Use first 16 characters of the hex hash as the brain server ID + // Use first 16 characters of the hex hash as the haxen server ID // This provides uniqueness while keeping the ID manageable - brainServerID := hex.EncodeToString(hash[:])[:16] + haxenServerID := hex.EncodeToString(hash[:])[:16] - return brainServerID + return haxenServerID } diff --git a/control-plane/internal/server/server_grpc_test.go b/control-plane/internal/server/server_grpc_test.go index 2cd5eef9..9ffa7bb6 100644 --- a/control-plane/internal/server/server_grpc_test.go +++ b/control-plane/internal/server/server_grpc_test.go @@ -8,9 +8,9 @@ import ( "testing" "time" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/adminpb" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/adminpb" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/stretchr/testify/require" ) @@ -23,8 +23,8 @@ func TestListReasonersAggregatesNodes(t *testing.T) { cfg := storage.StorageConfig{ Mode: "local", Local: storage.LocalStorageConfig{ - DatabasePath: filepath.Join(tempDir, "brain.db"), - KVStorePath: filepath.Join(tempDir, "brain.bolt"), + DatabasePath: filepath.Join(tempDir, "haxen.db"), + KVStorePath: filepath.Join(tempDir, "haxen.bolt"), }, } @@ -37,7 +37,7 @@ func TestListReasonersAggregatesNodes(t *testing.T) { } t.Cleanup(func() { _ = localStore.Close(ctx) }) - srv := &BrainServer{storage: localStore} + srv := &HaxenServer{storage: localStore} schema := json.RawMessage("{}") node := &types.AgentNode{ diff --git a/control-plane/internal/server/server_routes_test.go b/control-plane/internal/server/server_routes_test.go index 7980a44b..bf19509e 100644 --- a/control-plane/internal/server/server_routes_test.go +++ b/control-plane/internal/server/server_routes_test.go @@ -5,8 +5,8 @@ import ( "net/http/httptest" "testing" - "github.com/your-org/brain/control-plane/internal/config" - "github.com/your-org/brain/control-plane/internal/services" + "github.com/your-org/haxen/control-plane/internal/config" + "github.com/your-org/haxen/control-plane/internal/services" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" @@ -17,7 +17,7 @@ func TestSetupRoutesRegistersMetricsAndUI(t *testing.T) { gin.SetMode(gin.TestMode) - srv := &BrainServer{ + srv := &HaxenServer{ Router: gin.New(), config: &config.Config{ UI: config.UIConfig{Enabled: true, Mode: "embedded"}, @@ -54,7 +54,7 @@ func TestUnregisterAgentFromMonitoringResponses(t *testing.T) { gin.SetMode(gin.TestMode) - srv := &BrainServer{} + srv := &HaxenServer{} t.Run("missing node id returns 400", func(t *testing.T) { req, _ := http.NewRequest(http.MethodDelete, "/internal/nodes//monitor", nil) diff --git a/control-plane/internal/server/server_test.go b/control-plane/internal/server/server_test.go index 176a7931..63c61e1f 100644 --- a/control-plane/internal/server/server_test.go +++ b/control-plane/internal/server/server_test.go @@ -11,14 +11,14 @@ import ( "testing" "time" - "github.com/your-org/brain/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/internal/storage" "github.com/gin-gonic/gin" "gopkg.in/yaml.v3" ) func TestCheckStorageHealthOverride(t *testing.T) { - srv := &BrainServer{ + srv := &HaxenServer{ storageHealthOverride: func(context.Context) gin.H { return gin.H{"status": "healthy"} }, @@ -31,7 +31,7 @@ func TestCheckStorageHealthOverride(t *testing.T) { } func TestCheckStorageHealthWithoutStorage(t *testing.T) { - srv := &BrainServer{} + srv := &HaxenServer{} result := srv.checkStorageHealth(context.Background()) if status, ok := result["status"].(string); !ok || status != "healthy" { t.Fatalf("expected default healthy status when storage nil, got %+v", result) @@ -39,7 +39,7 @@ func TestCheckStorageHealthWithoutStorage(t *testing.T) { } func TestCheckStorageHealthContextError(t *testing.T) { - srv := &BrainServer{} + srv := &HaxenServer{} ctx, cancel := context.WithCancel(context.Background()) cancel() @@ -108,7 +108,7 @@ func (c *fakeCache) Publish(channel string, message interface{}) error { func TestCheckCacheHealthHealthy(t *testing.T) { cache := newFakeCache() - srv := &BrainServer{cache: cache} + srv := &HaxenServer{cache: cache} result := srv.checkCacheHealth(context.Background()) if status, ok := result["status"].(string); !ok || status != "healthy" { @@ -119,7 +119,7 @@ func TestCheckCacheHealthHealthy(t *testing.T) { func TestCheckCacheHealthSetError(t *testing.T) { cache := newFakeCache() cache.setErr = context.DeadlineExceeded - srv := &BrainServer{cache: cache} + srv := &HaxenServer{cache: cache} result := srv.checkCacheHealth(context.Background()) if status, ok := result["status"].(string); !ok || status != "unhealthy" { @@ -130,7 +130,7 @@ func TestCheckCacheHealthSetError(t *testing.T) { func TestCheckCacheHealthGetError(t *testing.T) { cache := newFakeCache() cache.getErr = context.DeadlineExceeded - srv := &BrainServer{cache: cache} + srv := &HaxenServer{cache: cache} result := srv.checkCacheHealth(context.Background()) if status, ok := result["status"].(string); !ok || status != "unhealthy" { @@ -140,7 +140,7 @@ func TestCheckCacheHealthGetError(t *testing.T) { func TestHealthCheckHandlerHealthy(t *testing.T) { gin.SetMode(gin.TestMode) - srv := &BrainServer{ + srv := &HaxenServer{ storageHealthOverride: func(context.Context) gin.H { return gin.H{"status": "healthy"} }, cacheHealthOverride: func(context.Context) gin.H { return gin.H{"status": "healthy"} }, } @@ -167,7 +167,7 @@ func TestHealthCheckHandlerHealthy(t *testing.T) { func TestHealthCheckHandlerCacheOptional(t *testing.T) { gin.SetMode(gin.TestMode) - srv := &BrainServer{ + srv := &HaxenServer{ storageHealthOverride: func(context.Context) gin.H { return gin.H{"status": "healthy"} }, } @@ -195,7 +195,7 @@ func TestHealthCheckHandlerCacheOptional(t *testing.T) { func TestHealthCheckHandlerUnhealthyStorage(t *testing.T) { gin.SetMode(gin.TestMode) - srv := &BrainServer{ + srv := &HaxenServer{ storageHealthOverride: func(context.Context) gin.H { return gin.H{"status": "unhealthy"} }, cacheHealthOverride: func(context.Context) gin.H { return gin.H{"status": "healthy"} }, } @@ -214,7 +214,7 @@ func TestHealthCheckHandlerUnhealthyStorage(t *testing.T) { func TestHealthCheckHandlerWithoutStorage(t *testing.T) { gin.SetMode(gin.TestMode) - srv := &BrainServer{} + srv := &HaxenServer{} w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) @@ -228,13 +228,13 @@ func TestHealthCheckHandlerWithoutStorage(t *testing.T) { } } -func TestGenerateBrainServerIDDeterministic(t *testing.T) { - dir1 := filepath.Join("/tmp", "brain-test-1") - dir2 := filepath.Join("/tmp", "brain-test-2") +func TestGenerateHaxenServerIDDeterministic(t *testing.T) { + dir1 := filepath.Join("/tmp", "haxen-test-1") + dir2 := filepath.Join("/tmp", "haxen-test-2") - id1 := generateBrainServerID(dir1) - id1Again := generateBrainServerID(dir1) - id2 := generateBrainServerID(dir2) + id1 := generateHaxenServerID(dir1) + id1Again := generateHaxenServerID(dir1) + id2 := generateHaxenServerID(dir2) if id1 != id1Again { t.Fatal("expected deterministic ID for same path") @@ -246,7 +246,7 @@ func TestGenerateBrainServerIDDeterministic(t *testing.T) { func TestUnregisterAgentFromMonitoring_NoNodeID(t *testing.T) { gin.SetMode(gin.TestMode) - srv := &BrainServer{} + srv := &HaxenServer{} router := gin.New() router.DELETE("/nodes/:node_id/monitoring", srv.unregisterAgentFromMonitoring) @@ -262,7 +262,7 @@ func TestUnregisterAgentFromMonitoring_NoNodeID(t *testing.T) { func TestUnregisterAgentFromMonitoring_NoMonitor(t *testing.T) { gin.SetMode(gin.TestMode) - srv := &BrainServer{} + srv := &HaxenServer{} router := gin.New() router.DELETE("/nodes/:node_id/monitoring", srv.unregisterAgentFromMonitoring) @@ -279,30 +279,30 @@ func TestUnregisterAgentFromMonitoring_NoMonitor(t *testing.T) { func TestSyncPackagesFromRegistry(t *testing.T) { storage := newStubPackageStorage() - brainHome := t.TempDir() - pkgDir := filepath.Join(brainHome, "packages", "mypkg") + haxenHome := t.TempDir() + pkgDir := filepath.Join(haxenHome, "packages", "mypkg") if err := os.MkdirAll(pkgDir, 0o755); err != nil { t.Fatalf("failed to create package dir: %v", err) } packageContent := []byte(`name: Test Package\nversion: 1.0.0`) - if err := os.WriteFile(filepath.Join(pkgDir, "brain-package.yaml"), packageContent, 0o644); err != nil { - t.Fatalf("failed to write brain-package.yaml: %v", err) + if err := os.WriteFile(filepath.Join(pkgDir, "haxen-package.yaml"), packageContent, 0o644); err != nil { + t.Fatalf("failed to write haxen-package.yaml: %v", err) } installedContent := []byte("installed:\n test-package:\n name: Test Package\n version: \"1.0.0\"\n description: Test description\n path: \"" + pkgDir + "\"\n source: local\n") - if err := os.WriteFile(filepath.Join(brainHome, "installed.yaml"), installedContent, 0o644); err != nil { + if err := os.WriteFile(filepath.Join(haxenHome, "installed.yaml"), installedContent, 0o644); err != nil { t.Fatalf("failed to write installed.yaml: %v", err) } var reg InstallationRegistry - if data, err := os.ReadFile(filepath.Join(brainHome, "installed.yaml")); err == nil { + if data, err := os.ReadFile(filepath.Join(haxenHome, "installed.yaml")); err == nil { _ = yaml.Unmarshal(data, ®) } if len(reg.Installed) == 0 { t.Fatal("expected registry to contain installed package") } - if err := SyncPackagesFromRegistry(brainHome, storage); err != nil { + if err := SyncPackagesFromRegistry(haxenHome, storage); err != nil { t.Fatalf("SyncPackagesFromRegistry returned error: %v", err) } @@ -313,9 +313,9 @@ func TestSyncPackagesFromRegistry(t *testing.T) { func TestSyncPackagesFromRegistryMissingFile(t *testing.T) { storage := newStubPackageStorage() - brainHome := t.TempDir() + haxenHome := t.TempDir() - if err := SyncPackagesFromRegistry(brainHome, storage); err != nil { + if err := SyncPackagesFromRegistry(haxenHome, storage); err != nil { t.Fatalf("expected nil error when registry file missing, got %v", err) } if len(storage.packages) != 0 { diff --git a/control-plane/internal/server/test_helpers_test.go b/control-plane/internal/server/test_helpers_test.go index f6c9b1ea..544262a1 100644 --- a/control-plane/internal/server/test_helpers_test.go +++ b/control-plane/internal/server/test_helpers_test.go @@ -4,7 +4,7 @@ import ( "context" "fmt" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" ) type stubPackageStorage struct { diff --git a/control-plane/internal/services/did_registry.go b/control-plane/internal/services/did_registry.go index 325775a3..cca85ea7 100644 --- a/control-plane/internal/services/did_registry.go +++ b/control-plane/internal/services/did_registry.go @@ -5,8 +5,8 @@ import ( "fmt" "sync" - "github.com/your-org/brain/control-plane/pkg/types" - "github.com/your-org/brain/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/storage" ) // DIDRegistry manages the storage and retrieval of DID registries using database-only operations. @@ -34,13 +34,13 @@ func (r *DIDRegistry) Initialize() error { return r.loadRegistriesFromDatabase() } -// GetRegistry retrieves a DID registry for a brain server. +// GetRegistry retrieves a DID registry for a haxen server. // Returns (nil, nil) if registry doesn't exist, (nil, error) for actual errors. -func (r *DIDRegistry) GetRegistry(brainServerID string) (*types.DIDRegistry, error) { +func (r *DIDRegistry) GetRegistry(haxenServerID string) (*types.DIDRegistry, error) { r.mu.RLock() defer r.mu.RUnlock() - registry, exists := r.registries[brainServerID] + registry, exists := r.registries[haxenServerID] if !exists { // Return nil, nil for "not found" to distinguish from actual errors return nil, nil @@ -49,19 +49,19 @@ func (r *DIDRegistry) GetRegistry(brainServerID string) (*types.DIDRegistry, err return registry, nil } -// StoreRegistry stores a DID registry for a brain server. +// StoreRegistry stores a DID registry for a haxen server. func (r *DIDRegistry) StoreRegistry(registry *types.DIDRegistry) error { r.mu.Lock() defer r.mu.Unlock() // Store in memory - r.registries[registry.BrainServerID] = registry + r.registries[registry.HaxenServerID] = registry // Persist to database return r.saveRegistryToDatabase(registry) } -// ListRegistries lists all brain server registries. +// ListRegistries lists all haxen server registries. func (r *DIDRegistry) ListRegistries() ([]*types.DIDRegistry, error) { r.mu.RLock() defer r.mu.RUnlock() @@ -74,13 +74,13 @@ func (r *DIDRegistry) ListRegistries() ([]*types.DIDRegistry, error) { return registries, nil } -// DeleteRegistry deletes a DID registry for a brain server. -func (r *DIDRegistry) DeleteRegistry(brainServerID string) error { +// DeleteRegistry deletes a DID registry for a haxen server. +func (r *DIDRegistry) DeleteRegistry(haxenServerID string) error { r.mu.Lock() defer r.mu.Unlock() // Remove from memory - delete(r.registries, brainServerID) + delete(r.registries, haxenServerID) // TODO: Add database deletion method to storage interface // For now, we'll just remove from memory @@ -88,13 +88,13 @@ func (r *DIDRegistry) DeleteRegistry(brainServerID string) error { } // UpdateAgentStatus updates the status of an agent DID. -func (r *DIDRegistry) UpdateAgentStatus(brainServerID, agentNodeID string, status types.AgentDIDStatus) error { +func (r *DIDRegistry) UpdateAgentStatus(haxenServerID, agentNodeID string, status types.AgentDIDStatus) error { r.mu.Lock() defer r.mu.Unlock() - registry, exists := r.registries[brainServerID] + registry, exists := r.registries[haxenServerID] if !exists { - return fmt.Errorf("registry not found for brain server: %s", brainServerID) + return fmt.Errorf("registry not found for haxen server: %s", haxenServerID) } agentInfo, exists := registry.AgentNodes[agentNodeID] @@ -110,13 +110,13 @@ func (r *DIDRegistry) UpdateAgentStatus(brainServerID, agentNodeID string, statu } // FindDIDByComponent finds a DID by component type and function name. -func (r *DIDRegistry) FindDIDByComponent(brainServerID, componentType, functionName string) (*types.DIDIdentity, error) { +func (r *DIDRegistry) FindDIDByComponent(haxenServerID, componentType, functionName string) (*types.DIDIdentity, error) { r.mu.RLock() defer r.mu.RUnlock() - registry, exists := r.registries[brainServerID] + registry, exists := r.registries[haxenServerID] if !exists { - return nil, fmt.Errorf("registry not found for brain server: %s", brainServerID) + return nil, fmt.Errorf("registry not found for haxen server: %s", haxenServerID) } // Search through all agent nodes @@ -162,13 +162,13 @@ func (r *DIDRegistry) FindDIDByComponent(brainServerID, componentType, functionN } // GetAgentDIDs retrieves all DIDs for a specific agent node. -func (r *DIDRegistry) GetAgentDIDs(brainServerID, agentNodeID string) (*types.DIDIdentityPackage, error) { +func (r *DIDRegistry) GetAgentDIDs(haxenServerID, agentNodeID string) (*types.DIDIdentityPackage, error) { r.mu.RLock() defer r.mu.RUnlock() - registry, exists := r.registries[brainServerID] + registry, exists := r.registries[haxenServerID] if !exists { - return nil, fmt.Errorf("registry not found for brain server: %s", brainServerID) + return nil, fmt.Errorf("registry not found for haxen server: %s", haxenServerID) } agentInfo, exists := registry.AgentNodes[agentNodeID] @@ -208,7 +208,7 @@ func (r *DIDRegistry) GetAgentDIDs(brainServerID, agentNodeID string) (*types.DI }, ReasonerDIDs: reasonerDIDs, SkillDIDs: skillDIDs, - BrainServerID: brainServerID, + HaxenServerID: haxenServerID, }, nil } @@ -219,39 +219,39 @@ func (r *DIDRegistry) loadRegistriesFromDatabase() error { } ctx := context.Background() - // Load brain server DID information - brainServerDIDs, err := r.storageProvider.ListBrainServerDIDs(ctx) + // Load haxen server DID information + haxenServerDIDs, err := r.storageProvider.ListHaxenServerDIDs(ctx) if err != nil { - return fmt.Errorf("failed to list brain server DIDs: %w", err) + return fmt.Errorf("failed to list haxen server DIDs: %w", err) } - // Create registries for each brain server - for _, brainServerDIDInfo := range brainServerDIDs { + // Create registries for each haxen server + for _, haxenServerDIDInfo := range haxenServerDIDs { registry := &types.DIDRegistry{ - BrainServerID: brainServerDIDInfo.BrainServerID, - RootDID: brainServerDIDInfo.RootDID, - MasterSeed: brainServerDIDInfo.MasterSeed, + HaxenServerID: haxenServerDIDInfo.HaxenServerID, + RootDID: haxenServerDIDInfo.RootDID, + MasterSeed: haxenServerDIDInfo.MasterSeed, AgentNodes: make(map[string]types.AgentDIDInfo), TotalDIDs: 0, - CreatedAt: brainServerDIDInfo.CreatedAt, - LastKeyRotation: brainServerDIDInfo.LastKeyRotation, + CreatedAt: haxenServerDIDInfo.CreatedAt, + LastKeyRotation: haxenServerDIDInfo.LastKeyRotation, } - // Load agent DIDs for this brain server + // Load agent DIDs for this haxen server agentDIDs, err := r.storageProvider.ListAgentDIDs(ctx) if err != nil { return fmt.Errorf("failed to list agent DIDs: %w", err) } for _, agentDIDInfo := range agentDIDs { - // Filter agents for this brain server (assuming we can match by some criteria) - // For now, we'll add all agents to the default brain server - // TODO: Add brain server filtering when the storage interface supports it + // Filter agents for this haxen server (assuming we can match by some criteria) + // For now, we'll add all agents to the default haxen server + // TODO: Add haxen server filtering when the storage interface supports it agentInfo := types.AgentDIDInfo{ DID: agentDIDInfo.DID, AgentNodeID: agentDIDInfo.AgentNodeID, - BrainServerID: brainServerDIDInfo.BrainServerID, + HaxenServerID: haxenServerDIDInfo.HaxenServerID, PublicKeyJWK: agentDIDInfo.PublicKeyJWK, DerivationPath: agentDIDInfo.DerivationPath, Status: agentDIDInfo.Status, @@ -296,7 +296,7 @@ func (r *DIDRegistry) loadRegistriesFromDatabase() error { registry.TotalDIDs++ } - r.registries[brainServerDIDInfo.BrainServerID] = registry + r.registries[haxenServerDIDInfo.HaxenServerID] = registry } return nil @@ -309,17 +309,17 @@ func (r *DIDRegistry) saveRegistryToDatabase(registry *types.DIDRegistry) error } ctx := context.Background() - // Store brain server DID information - err := r.storageProvider.StoreBrainServerDID( + // Store haxen server DID information + err := r.storageProvider.StoreHaxenServerDID( ctx, - registry.BrainServerID, + registry.HaxenServerID, registry.RootDID, registry.MasterSeed, registry.CreatedAt, registry.LastKeyRotation, ) if err != nil { - return fmt.Errorf("failed to store brain server DID: %w", err) + return fmt.Errorf("failed to store haxen server DID: %w", err) } // Store each agent DID and its components using transaction-safe method @@ -359,7 +359,7 @@ func (r *DIDRegistry) saveRegistryToDatabase(registry *types.DIDRegistry) error ctx, agentInfo.AgentNodeID, agentInfo.DID, - registry.BrainServerID, // Use brain server ID instead of root DID + registry.HaxenServerID, // Use haxen server ID instead of root DID string(agentInfo.PublicKeyJWK), derivationIndex, components, diff --git a/control-plane/internal/services/did_registry_test.go b/control-plane/internal/services/did_registry_test.go index 99777147..aa3973ca 100644 --- a/control-plane/internal/services/did_registry_test.go +++ b/control-plane/internal/services/did_registry_test.go @@ -7,8 +7,8 @@ import ( "testing" "time" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/stretchr/testify/require" ) @@ -21,8 +21,8 @@ func setupTestStorage(t *testing.T) (storage.StorageProvider, context.Context) { cfg := storage.StorageConfig{ Mode: "local", Local: storage.LocalStorageConfig{ - DatabasePath: filepath.Join(tempDir, "brain.db"), - KVStorePath: filepath.Join(tempDir, "brain.bolt"), + DatabasePath: filepath.Join(tempDir, "haxen.db"), + KVStorePath: filepath.Join(tempDir, "haxen.bolt"), }, } @@ -44,10 +44,10 @@ func setupTestStorage(t *testing.T) (storage.StorageProvider, context.Context) { func TestDIDRegistryInitializeAndLookup(t *testing.T) { provider, ctx := setupTestStorage(t) - brainID := "brain-1" + haxenID := "haxen-1" now := time.Now().UTC().Truncate(time.Second) - require.NoError(t, provider.StoreBrainServerDID(ctx, brainID, "did:brain:root", []byte("seed"), now, now)) + require.NoError(t, provider.StoreHaxenServerDID(ctx, haxenID, "did:haxen:root", []byte("seed"), now, now)) components := []storage.ComponentDIDRequest{ { @@ -66,34 +66,34 @@ func TestDIDRegistryInitializeAndLookup(t *testing.T) { }, } - require.NoError(t, provider.StoreAgentDIDWithComponents(ctx, "agent-1", "did:agent:1", brainID, "{}", 0, components)) + require.NoError(t, provider.StoreAgentDIDWithComponents(ctx, "agent-1", "did:agent:1", haxenID, "{}", 0, components)) registry := NewDIDRegistryWithStorage(provider) require.NoError(t, registry.Initialize()) - loaded, err := registry.GetRegistry(brainID) + loaded, err := registry.GetRegistry(haxenID) require.NoError(t, err) require.NotNil(t, loaded) require.Contains(t, loaded.AgentNodes, "agent-1") // Validate reasoner lookup - reasonerID, err := registry.FindDIDByComponent(brainID, "reasoner", "reasoner.fn") + reasonerID, err := registry.FindDIDByComponent(haxenID, "reasoner", "reasoner.fn") require.NoError(t, err) require.Equal(t, "did:reasoner:1", reasonerID.DID) // Validate skill lookup - skillID, err := registry.FindDIDByComponent(brainID, "skill", "skill.fn") + skillID, err := registry.FindDIDByComponent(haxenID, "skill", "skill.fn") require.NoError(t, err) require.Equal(t, "did:skill:1", skillID.DID) // Update status and ensure it is persisted in-memory - require.NoError(t, registry.UpdateAgentStatus(brainID, "agent-1", types.AgentDIDStatusActive)) + require.NoError(t, registry.UpdateAgentStatus(haxenID, "agent-1", types.AgentDIDStatusActive)) - loadedAfterUpdate, err := registry.GetRegistry(brainID) + loadedAfterUpdate, err := registry.GetRegistry(haxenID) require.NoError(t, err) require.Equal(t, types.AgentDIDStatusActive, loadedAfterUpdate.AgentNodes["agent-1"].Status) - packageResult, err := registry.GetAgentDIDs(brainID, "agent-1") + packageResult, err := registry.GetAgentDIDs(haxenID, "agent-1") require.NoError(t, err) require.Equal(t, "did:agent:1", packageResult.AgentDID.DID) require.Contains(t, packageResult.ReasonerDIDs, "reasoner.fn") diff --git a/control-plane/internal/services/did_service.go b/control-plane/internal/services/did_service.go index d23806ae..dbd7a566 100644 --- a/control-plane/internal/services/did_service.go +++ b/control-plane/internal/services/did_service.go @@ -11,10 +11,10 @@ import ( "hash/fnv" "time" - "github.com/your-org/brain/control-plane/internal/config" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/config" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" ) // DIDService handles DID generation, management, and resolution. @@ -22,7 +22,7 @@ type DIDService struct { config *config.DIDConfig keystore *KeystoreService registry *DIDRegistry - brainServerID string + haxenServerID string } // NewDIDService creates a new DID service instance. @@ -31,27 +31,27 @@ func NewDIDService(cfg *config.DIDConfig, keystore *KeystoreService, registry *D config: cfg, keystore: keystore, registry: registry, - brainServerID: "", // Will be set during initialization + haxenServerID: "", // Will be set during initialization } } -// Initialize initializes the DID service and creates brain server master seed if needed. -func (s *DIDService) Initialize(brainServerID string) error { +// Initialize initializes the DID service and creates haxen server master seed if needed. +func (s *DIDService) Initialize(haxenServerID string) error { if !s.config.Enabled { return nil } - // Store the brain server ID for dynamic resolution - s.brainServerID = brainServerID + // Store the haxen server ID for dynamic resolution + s.haxenServerID = haxenServerID - // Check if brain server already has a DID registry - registry, err := s.registry.GetRegistry(brainServerID) + // Check if haxen server already has a DID registry + registry, err := s.registry.GetRegistry(haxenServerID) if err != nil { return fmt.Errorf("failed to check existing registry: %w", err) } if registry == nil { - // Create new brain server registry + // Create new haxen server registry masterSeed := make([]byte, 32) if _, err := rand.Read(masterSeed); err != nil { return fmt.Errorf("failed to generate master seed: %w", err) @@ -65,7 +65,7 @@ func (s *DIDService) Initialize(brainServerID string) error { // Create and store registry registry = &types.DIDRegistry{ - BrainServerID: brainServerID, + HaxenServerID: haxenServerID, MasterSeed: masterSeed, RootDID: rootDID, AgentNodes: make(map[string]types.AgentDIDInfo), @@ -83,45 +83,45 @@ func (s *DIDService) Initialize(brainServerID string) error { return nil } -// GetBrainServerID returns the brain server ID for this DID service instance. -// This method provides dynamic brain server ID resolution instead of hardcoded "default". -func (s *DIDService) GetBrainServerID() (string, error) { - if s.brainServerID == "" { - return "", fmt.Errorf("brain server ID not initialized - call Initialize() first") +// GetHaxenServerID returns the haxen server ID for this DID service instance. +// This method provides dynamic haxen server ID resolution instead of hardcoded "default". +func (s *DIDService) GetHaxenServerID() (string, error) { + if s.haxenServerID == "" { + return "", fmt.Errorf("haxen server ID not initialized - call Initialize() first") } - return s.brainServerID, nil + return s.haxenServerID, nil } -// getBrainServerID is an internal helper that returns the brain server ID. -func (s *DIDService) getBrainServerID() (string, error) { - return s.GetBrainServerID() +// getHaxenServerID is an internal helper that returns the haxen server ID. +func (s *DIDService) getHaxenServerID() (string, error) { + return s.GetHaxenServerID() } -// validateBrainServerRegistry ensures that the brain server registry exists before operations. -func (s *DIDService) validateBrainServerRegistry() error { - brainServerID, err := s.getBrainServerID() +// validateHaxenServerRegistry ensures that the haxen server registry exists before operations. +func (s *DIDService) validateHaxenServerRegistry() error { + haxenServerID, err := s.getHaxenServerID() if err != nil { return err } - registry, err := s.registry.GetRegistry(brainServerID) + registry, err := s.registry.GetRegistry(haxenServerID) if err != nil { - return fmt.Errorf("failed to get brain server registry: %w", err) + return fmt.Errorf("failed to get haxen server registry: %w", err) } if registry == nil { - return fmt.Errorf("brain server registry not found for ID: %s - ensure Initialize() was called", brainServerID) + return fmt.Errorf("haxen server registry not found for ID: %s - ensure Initialize() was called", haxenServerID) } return nil } -// GetRegistry retrieves a DID registry for a brain server. -func (s *DIDService) GetRegistry(brainServerID string) (*types.DIDRegistry, error) { +// GetRegistry retrieves a DID registry for a haxen server. +func (s *DIDService) GetRegistry(haxenServerID string) (*types.DIDRegistry, error) { if !s.config.Enabled { return nil, fmt.Errorf("DID system is disabled") } - return s.registry.GetRegistry(brainServerID) + return s.registry.GetRegistry(haxenServerID) } // RegisterAgent generates DIDs for an agent node and all its components. @@ -134,11 +134,11 @@ func (s *DIDService) RegisterAgent(req *types.DIDRegistrationRequest) (*types.DI }, nil } - // Validate brain server registry exists - if err := s.validateBrainServerRegistry(); err != nil { + // Validate haxen server registry exists + if err := s.validateHaxenServerRegistry(); err != nil { return &types.DIDRegistrationResponse{ Success: false, - Error: fmt.Sprintf("brain server registry validation failed: %v", err), + Error: fmt.Sprintf("haxen server registry validation failed: %v", err), }, nil } @@ -184,17 +184,17 @@ func (s *DIDService) RegisterAgent(req *types.DIDRegistrationRequest) (*types.DI // handleNewRegistration handles registration for new agents (original logic). func (s *DIDService) handleNewRegistration(req *types.DIDRegistrationRequest) (*types.DIDRegistrationResponse, error) { - // Get brain server ID dynamically - brainServerID, err := s.getBrainServerID() + // Get haxen server ID dynamically + haxenServerID, err := s.getHaxenServerID() if err != nil { return &types.DIDRegistrationResponse{ Success: false, - Error: fmt.Sprintf("failed to get brain server ID: %v", err), + Error: fmt.Sprintf("failed to get haxen server ID: %v", err), }, nil } - // Get brain server registry using dynamic ID - registry, err := s.registry.GetRegistry(brainServerID) + // Get haxen server registry using dynamic ID + registry, err := s.registry.GetRegistry(haxenServerID) if err != nil { return &types.DIDRegistrationResponse{ Success: false, @@ -202,14 +202,14 @@ func (s *DIDService) handleNewRegistration(req *types.DIDRegistrationRequest) (* }, nil } - // Generate brain server hash for derivation path - brainServerHash := s.hashBrainServerID(registry.BrainServerID) + // Generate haxen server hash for derivation path + haxenServerHash := s.hashHaxenServerID(registry.HaxenServerID) // Get next agent index agentIndex := len(registry.AgentNodes) // Generate agent DID - agentPath := fmt.Sprintf("m/44'/%d'/%d'", brainServerHash, agentIndex) + agentPath := fmt.Sprintf("m/44'/%d'/%d'", haxenServerHash, agentIndex) agentDID, agentPrivKey, agentPubKey, err := s.generateDIDWithKeys(registry.MasterSeed, agentPath) if err != nil { return &types.DIDRegistrationResponse{ @@ -232,7 +232,7 @@ func (s *DIDService) handleNewRegistration(req *types.DIDRegistrationRequest) (* continue } - reasonerPath := fmt.Sprintf("m/44'/%d'/%d'/0'/%d'", brainServerHash, agentIndex, validReasonerIndex) + reasonerPath := fmt.Sprintf("m/44'/%d'/%d'/0'/%d'", haxenServerHash, agentIndex, validReasonerIndex) reasonerDID, reasonerPrivKey, reasonerPubKey, err := s.generateDIDWithKeys(registry.MasterSeed, reasonerPath) if err != nil { return &types.DIDRegistrationResponse{ @@ -278,7 +278,7 @@ func (s *DIDService) handleNewRegistration(req *types.DIDRegistrationRequest) (* continue } - skillPath := fmt.Sprintf("m/44'/%d'/%d'/1'/%d'", brainServerHash, agentIndex, validSkillIndex) + skillPath := fmt.Sprintf("m/44'/%d'/%d'/1'/%d'", haxenServerHash, agentIndex, validSkillIndex) skillDID, skillPrivKey, skillPubKey, err := s.generateDIDWithKeys(registry.MasterSeed, skillPath) if err != nil { return &types.DIDRegistrationResponse{ @@ -347,7 +347,7 @@ func (s *DIDService) handleNewRegistration(req *types.DIDRegistrationRequest) (* }, ReasonerDIDs: reasonerDIDs, SkillDIDs: skillDIDs, - BrainServerID: registry.BrainServerID, + HaxenServerID: registry.HaxenServerID, } // Debug log the response structure @@ -370,24 +370,24 @@ func (s *DIDService) ResolveDID(did string) (*types.DIDIdentity, error) { return nil, fmt.Errorf("DID system is disabled") } - // Validate brain server registry exists - if err := s.validateBrainServerRegistry(); err != nil { - return nil, fmt.Errorf("brain server registry validation failed: %w", err) + // Validate haxen server registry exists + if err := s.validateHaxenServerRegistry(); err != nil { + return nil, fmt.Errorf("haxen server registry validation failed: %w", err) } - // Get brain server ID dynamically - brainServerID, err := s.getBrainServerID() + // Get haxen server ID dynamically + haxenServerID, err := s.getHaxenServerID() if err != nil { - return nil, fmt.Errorf("failed to get brain server ID: %w", err) + return nil, fmt.Errorf("failed to get haxen server ID: %w", err) } - // Get brain server registry using dynamic ID - registry, err := s.registry.GetRegistry(brainServerID) + // Get haxen server registry using dynamic ID + registry, err := s.registry.GetRegistry(haxenServerID) if err != nil { return nil, fmt.Errorf("failed to get DID registry: %w", err) } - // Check if this is the brain server root DID + // Check if this is the haxen server root DID if registry.RootDID == did { // Regenerate private key for root DID using root derivation path privateKeyJWK, err := s.regeneratePrivateKeyJWK(registry.MasterSeed, "m/44'/0'") @@ -406,7 +406,7 @@ func (s *DIDService) ResolveDID(did string) (*types.DIDIdentity, error) { PrivateKeyJWK: privateKeyJWK, PublicKeyJWK: publicKeyJWK, DerivationPath: "m/44'/0'", - ComponentType: "brain_server", + ComponentType: "haxen_server", }, nil } @@ -574,10 +574,10 @@ func (s *DIDService) ed25519PublicKeyToJWK(publicKey ed25519.PublicKey) (string, return string(jwkBytes), nil } -// hashBrainServerID creates a deterministic hash of brain server ID for derivation paths. -func (s *DIDService) hashBrainServerID(brainServerID string) uint32 { +// hashHaxenServerID creates a deterministic hash of haxen server ID for derivation paths. +func (s *DIDService) hashHaxenServerID(haxenServerID string) uint32 { h := fnv.New32a() - h.Write([]byte(brainServerID)) + h.Write([]byte(haxenServerID)) return h.Sum32() % (1 << 31) // Ensure it fits in BIP32 hardened derivation } @@ -624,19 +624,19 @@ func (s *DIDService) ListAllAgentDIDs() ([]string, error) { return nil, fmt.Errorf("DID system is disabled") } - // Validate brain server registry exists - if err := s.validateBrainServerRegistry(); err != nil { - return nil, fmt.Errorf("brain server registry validation failed: %w", err) + // Validate haxen server registry exists + if err := s.validateHaxenServerRegistry(); err != nil { + return nil, fmt.Errorf("haxen server registry validation failed: %w", err) } - // Get brain server ID dynamically - brainServerID, err := s.getBrainServerID() + // Get haxen server ID dynamically + haxenServerID, err := s.getHaxenServerID() if err != nil { - return nil, fmt.Errorf("failed to get brain server ID: %w", err) + return nil, fmt.Errorf("failed to get haxen server ID: %w", err) } - // Get brain server registry using dynamic ID - registry, err := s.registry.GetRegistry(brainServerID) + // Get haxen server registry using dynamic ID + registry, err := s.registry.GetRegistry(haxenServerID) if err != nil { return nil, fmt.Errorf("failed to get DID registry: %w", err) } @@ -669,19 +669,19 @@ func (s *DIDService) BackfillExistingNodes(ctx context.Context, storageProvider return nil } - // Validate brain server registry exists - if err := s.validateBrainServerRegistry(); err != nil { - return fmt.Errorf("brain server registry validation failed: %w", err) + // Validate haxen server registry exists + if err := s.validateHaxenServerRegistry(); err != nil { + return fmt.Errorf("haxen server registry validation failed: %w", err) } - // Get brain server ID dynamically - brainServerID, err := s.getBrainServerID() + // Get haxen server ID dynamically + haxenServerID, err := s.getHaxenServerID() if err != nil { - return fmt.Errorf("failed to get brain server ID: %w", err) + return fmt.Errorf("failed to get haxen server ID: %w", err) } // Get current DID registry using dynamic ID - registry, err := s.GetRegistry(brainServerID) + registry, err := s.GetRegistry(haxenServerID) if err != nil { return fmt.Errorf("failed to get DID registry: %w", err) } @@ -728,19 +728,19 @@ func (s *DIDService) GetExistingAgentDID(agentNodeID string) (*types.AgentDIDInf return nil, fmt.Errorf("DID system is disabled") } - // Validate brain server registry exists - if err := s.validateBrainServerRegistry(); err != nil { - return nil, fmt.Errorf("brain server registry validation failed: %w", err) + // Validate haxen server registry exists + if err := s.validateHaxenServerRegistry(); err != nil { + return nil, fmt.Errorf("haxen server registry validation failed: %w", err) } - // Get brain server ID dynamically - brainServerID, err := s.getBrainServerID() + // Get haxen server ID dynamically + haxenServerID, err := s.getHaxenServerID() if err != nil { - return nil, fmt.Errorf("failed to get brain server ID: %w", err) + return nil, fmt.Errorf("failed to get haxen server ID: %w", err) } - // Get brain server registry using dynamic ID - registry, err := s.registry.GetRegistry(brainServerID) + // Get haxen server registry using dynamic ID + registry, err := s.registry.GetRegistry(haxenServerID) if err != nil { return nil, fmt.Errorf("failed to get DID registry: %w", err) } @@ -868,22 +868,22 @@ func (s *DIDService) findSkillByID(skills []types.SkillDefinition, id string) *t // generateReasonerPath generates a derivation path for a reasoner. func (s *DIDService) generateReasonerPath(agentNodeID, reasonerID string) string { - // Get brain server ID dynamically - brainServerID, err := s.getBrainServerID() + // Get haxen server ID dynamically + haxenServerID, err := s.getHaxenServerID() if err != nil { - logger.Logger.Error().Err(err).Msg("Failed to get brain server ID for reasoner path generation") + logger.Logger.Error().Err(err).Msg("Failed to get haxen server ID for reasoner path generation") return "" } // Get registry to find agent index - registry, err := s.registry.GetRegistry(brainServerID) + registry, err := s.registry.GetRegistry(haxenServerID) if err != nil { logger.Logger.Error().Err(err).Msg("Failed to get registry for reasoner path generation") return "" } - // Generate brain server hash for derivation path - brainServerHash := s.hashBrainServerID(registry.BrainServerID) + // Generate haxen server hash for derivation path + haxenServerHash := s.hashHaxenServerID(registry.HaxenServerID) // Find agent index (this is a simplified approach - in production you might want to store this) agentIndex := 0 @@ -898,27 +898,27 @@ func (s *DIDService) generateReasonerPath(agentNodeID, reasonerID string) string existingAgent := registry.AgentNodes[agentNodeID] reasonerIndex := len(existingAgent.Reasoners) - return fmt.Sprintf("m/44'/%d'/%d'/0'/%d'", brainServerHash, agentIndex, reasonerIndex) + return fmt.Sprintf("m/44'/%d'/%d'/0'/%d'", haxenServerHash, agentIndex, reasonerIndex) } // generateSkillPath generates a derivation path for a skill. func (s *DIDService) generateSkillPath(agentNodeID, skillID string) string { - // Get brain server ID dynamically - brainServerID, err := s.getBrainServerID() + // Get haxen server ID dynamically + haxenServerID, err := s.getHaxenServerID() if err != nil { - logger.Logger.Error().Err(err).Msg("Failed to get brain server ID for skill path generation") + logger.Logger.Error().Err(err).Msg("Failed to get haxen server ID for skill path generation") return "" } // Get registry to find agent index - registry, err := s.registry.GetRegistry(brainServerID) + registry, err := s.registry.GetRegistry(haxenServerID) if err != nil { logger.Logger.Error().Err(err).Msg("Failed to get registry for skill path generation") return "" } - // Generate brain server hash for derivation path - brainServerHash := s.hashBrainServerID(registry.BrainServerID) + // Generate haxen server hash for derivation path + haxenServerHash := s.hashHaxenServerID(registry.HaxenServerID) // Find agent index (this is a simplified approach - in production you might want to store this) agentIndex := 0 @@ -933,16 +933,16 @@ func (s *DIDService) generateSkillPath(agentNodeID, skillID string) string { existingAgent := registry.AgentNodes[agentNodeID] skillIndex := len(existingAgent.Skills) - return fmt.Sprintf("m/44'/%d'/%d'/1'/%d'", brainServerHash, agentIndex, skillIndex) + return fmt.Sprintf("m/44'/%d'/%d'/1'/%d'", haxenServerHash, agentIndex, skillIndex) } // buildExistingIdentityPackage builds an identity package from existing agent DID info. func (s *DIDService) buildExistingIdentityPackage(existingAgent *types.AgentDIDInfo) types.DIDIdentityPackage { - // Get brain server ID dynamically - brainServerID, err := s.getBrainServerID() + // Get haxen server ID dynamically + haxenServerID, err := s.getHaxenServerID() if err != nil { - logger.Logger.Error().Err(err).Msg("Failed to get brain server ID for identity package") - brainServerID = "unknown" + logger.Logger.Error().Err(err).Msg("Failed to get haxen server ID for identity package") + haxenServerID = "unknown" } // Build reasoner DIDs map @@ -981,7 +981,7 @@ func (s *DIDService) buildExistingIdentityPackage(existingAgent *types.AgentDIDI }, ReasonerDIDs: reasonerDIDs, SkillDIDs: skillDIDs, - BrainServerID: brainServerID, + HaxenServerID: haxenServerID, } } @@ -1054,25 +1054,25 @@ func (s *DIDService) PartialRegisterAgent(req *types.PartialDIDRegistrationReque }, nil } - // Validate brain server registry exists - if err := s.validateBrainServerRegistry(); err != nil { + // Validate haxen server registry exists + if err := s.validateHaxenServerRegistry(); err != nil { return &types.DIDRegistrationResponse{ Success: false, - Error: fmt.Sprintf("brain server registry validation failed: %v", err), + Error: fmt.Sprintf("haxen server registry validation failed: %v", err), }, nil } - // Get brain server ID dynamically - brainServerID, err := s.getBrainServerID() + // Get haxen server ID dynamically + haxenServerID, err := s.getHaxenServerID() if err != nil { return &types.DIDRegistrationResponse{ Success: false, - Error: fmt.Sprintf("failed to get brain server ID: %v", err), + Error: fmt.Sprintf("failed to get haxen server ID: %v", err), }, nil } - // Get brain server registry using dynamic ID - registry, err := s.registry.GetRegistry(brainServerID) + // Get haxen server registry using dynamic ID + registry, err := s.registry.GetRegistry(haxenServerID) if err != nil { return &types.DIDRegistrationResponse{ Success: false, @@ -1222,7 +1222,7 @@ func (s *DIDService) PartialRegisterAgent(req *types.PartialDIDRegistrationReque }, ReasonerDIDs: newReasonerDIDs, SkillDIDs: newSkillDIDs, - BrainServerID: registry.BrainServerID, + HaxenServerID: registry.HaxenServerID, } logger.Logger.Debug().Msgf("✅ Partial registration successful for agent %s: %d new reasoners, %d new skills", @@ -1244,25 +1244,25 @@ func (s *DIDService) DeregisterComponents(req *types.ComponentDeregistrationRequ }, nil } - // Validate brain server registry exists - if err := s.validateBrainServerRegistry(); err != nil { + // Validate haxen server registry exists + if err := s.validateHaxenServerRegistry(); err != nil { return &types.ComponentDeregistrationResponse{ Success: false, - Error: fmt.Sprintf("brain server registry validation failed: %v", err), + Error: fmt.Sprintf("haxen server registry validation failed: %v", err), }, nil } - // Get brain server ID dynamically - brainServerID, err := s.getBrainServerID() + // Get haxen server ID dynamically + haxenServerID, err := s.getHaxenServerID() if err != nil { return &types.ComponentDeregistrationResponse{ Success: false, - Error: fmt.Sprintf("failed to get brain server ID: %v", err), + Error: fmt.Sprintf("failed to get haxen server ID: %v", err), }, nil } - // Get brain server registry using dynamic ID - registry, err := s.registry.GetRegistry(brainServerID) + // Get haxen server registry using dynamic ID + registry, err := s.registry.GetRegistry(haxenServerID) if err != nil { return &types.ComponentDeregistrationResponse{ Success: false, diff --git a/control-plane/internal/services/did_service_test.go b/control-plane/internal/services/did_service_test.go index b7296963..6b346378 100644 --- a/control-plane/internal/services/did_service_test.go +++ b/control-plane/internal/services/did_service_test.go @@ -5,9 +5,9 @@ import ( "path/filepath" "testing" - "github.com/your-org/brain/control-plane/internal/config" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/config" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/stretchr/testify/require" ) @@ -27,14 +27,14 @@ func setupDIDTestEnvironment(t *testing.T) (*DIDService, *DIDRegistry, storage.S service := NewDIDService(cfg, ks, registry) - brainID := "brain-test" - require.NoError(t, service.Initialize(brainID)) + haxenID := "haxen-test" + require.NoError(t, service.Initialize(haxenID)) - return service, registry, provider, ctx, brainID + return service, registry, provider, ctx, haxenID } func TestDIDServiceRegisterAgentAndResolve(t *testing.T) { - service, registry, provider, ctx, brainID := setupDIDTestEnvironment(t) + service, registry, provider, ctx, haxenID := setupDIDTestEnvironment(t) req := &types.DIDRegistrationRequest{ AgentNodeID: "agent-alpha", @@ -49,7 +49,7 @@ func TestDIDServiceRegisterAgentAndResolve(t *testing.T) { require.Contains(t, resp.IdentityPackage.ReasonerDIDs, "reasoner.fn") require.Contains(t, resp.IdentityPackage.SkillDIDs, "skill.fn") - storedRegistry, err := registry.GetRegistry(brainID) + storedRegistry, err := registry.GetRegistry(haxenID) require.NoError(t, err) require.NotNil(t, storedRegistry) require.Contains(t, storedRegistry.AgentNodes, "agent-alpha") @@ -86,14 +86,14 @@ func TestDIDServiceValidateRegistryFailure(t *testing.T) { cfg := &config.DIDConfig{Enabled: true, Keystore: config.KeystoreConfig{Path: keystoreDir, Type: "local"}} service := NewDIDService(cfg, ks, registry) - err = service.validateBrainServerRegistry() + err = service.validateHaxenServerRegistry() require.Error(t, err) - brainID := "brain-validate" - require.NoError(t, service.Initialize(brainID)) - require.NoError(t, service.validateBrainServerRegistry()) + haxenID := "haxen-validate" + require.NoError(t, service.Initialize(haxenID)) + require.NoError(t, service.validateHaxenServerRegistry()) - stored, err := registry.GetRegistry(brainID) + stored, err := registry.GetRegistry(haxenID) require.NoError(t, err) require.NotNil(t, stored) require.False(t, stored.CreatedAt.IsZero()) diff --git a/control-plane/internal/services/execution_metrics.go b/control-plane/internal/services/execution_metrics.go index a1e22f58..5f2739ee 100644 --- a/control-plane/internal/services/execution_metrics.go +++ b/control-plane/internal/services/execution_metrics.go @@ -4,7 +4,7 @@ import ( "strings" "time" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -12,33 +12,33 @@ import ( var ( queueDepthGauge = promauto.NewGauge(prometheus.GaugeOpts{ - Name: "brain_gateway_queue_depth", + Name: "haxen_gateway_queue_depth", Help: "Number of workflow steps currently queued or in-flight for execution.", }) workerInflightGauge = promauto.NewGaugeVec(prometheus.GaugeOpts{ - Name: "brain_worker_inflight", + Name: "haxen_worker_inflight", Help: "Number of active worker executions grouped by agent node.", }, []string{"agent"}) stepDurationHistogram = promauto.NewHistogramVec(prometheus.HistogramOpts{ - Name: "brain_step_duration_seconds", + Name: "haxen_step_duration_seconds", Help: "Duration of workflow step executions split by terminal status.", Buckets: prometheus.DefBuckets, }, []string{"status"}) stepRetriesCounter = promauto.NewCounterVec(prometheus.CounterOpts{ - Name: "brain_step_retries_total", + Name: "haxen_step_retries_total", Help: "Total number of workflow step retry attempts grouped by agent node.", }, []string{"agent"}) waiterInflightGauge = promauto.NewGauge(prometheus.GaugeOpts{ - Name: "brain_waiters_inflight", + Name: "haxen_waiters_inflight", Help: "Number of synchronous waiter channels currently registered.", }) backpressureCounter = promauto.NewCounterVec(prometheus.CounterOpts{ - Name: "brain_gateway_backpressure_total", + Name: "haxen_gateway_backpressure_total", Help: "Count of backpressure events emitted by the execution gateway grouped by reason.", }, []string{"reason"}) ) diff --git a/control-plane/internal/services/executions_ui_service.go b/control-plane/internal/services/executions_ui_service.go index 8a0a6cce..f028a3c4 100644 --- a/control-plane/internal/services/executions_ui_service.go +++ b/control-plane/internal/services/executions_ui_service.go @@ -1,14 +1,14 @@ package services import ( - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "context" "fmt" "sync" "time" - "github.com/your-org/brain/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/logger" ) // ExecutionEvent represents a real-time event related to executions. diff --git a/control-plane/internal/services/health_monitor.go b/control-plane/internal/services/health_monitor.go index ff49b9e1..ef3375a0 100644 --- a/control-plane/internal/services/health_monitor.go +++ b/control-plane/internal/services/health_monitor.go @@ -1,12 +1,12 @@ package services import ( - "github.com/your-org/brain/control-plane/internal/core/domain" - "github.com/your-org/brain/control-plane/internal/core/interfaces" - "github.com/your-org/brain/control-plane/internal/events" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/core/domain" + "github.com/your-org/haxen/control-plane/internal/core/interfaces" + "github.com/your-org/haxen/control-plane/internal/events" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "context" "sync" "time" diff --git a/control-plane/internal/services/keystore_service.go b/control-plane/internal/services/keystore_service.go index d95a350b..97793e53 100644 --- a/control-plane/internal/services/keystore_service.go +++ b/control-plane/internal/services/keystore_service.go @@ -9,7 +9,7 @@ import ( "os" "path/filepath" - "github.com/your-org/brain/control-plane/internal/config" + "github.com/your-org/haxen/control-plane/internal/config" ) // KeystoreService handles secure storage and management of cryptographic keys. diff --git a/control-plane/internal/services/keystore_service_test.go b/control-plane/internal/services/keystore_service_test.go index b44dcb62..b8104e20 100644 --- a/control-plane/internal/services/keystore_service_test.go +++ b/control-plane/internal/services/keystore_service_test.go @@ -6,7 +6,7 @@ import ( "path/filepath" "testing" - "github.com/your-org/brain/control-plane/internal/config" + "github.com/your-org/haxen/control-plane/internal/config" "github.com/stretchr/testify/require" ) diff --git a/control-plane/internal/services/presence_manager.go b/control-plane/internal/services/presence_manager.go index 81a9b635..6b49e22f 100644 --- a/control-plane/internal/services/presence_manager.go +++ b/control-plane/internal/services/presence_manager.go @@ -5,8 +5,8 @@ import ( "sync" "time" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/pkg/types" ) type PresenceManagerConfig struct { diff --git a/control-plane/internal/services/status_manager.go b/control-plane/internal/services/status_manager.go index 3b1f2fcb..264d129e 100644 --- a/control-plane/internal/services/status_manager.go +++ b/control-plane/internal/services/status_manager.go @@ -6,11 +6,11 @@ import ( "sync" "time" - "github.com/your-org/brain/control-plane/internal/core/interfaces" - "github.com/your-org/brain/control-plane/internal/events" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/core/interfaces" + "github.com/your-org/haxen/control-plane/internal/events" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" ) // StatusManagerConfig holds configuration for the status manager diff --git a/control-plane/internal/services/status_manager_test.go b/control-plane/internal/services/status_manager_test.go index f7d6ca13..44b5e83a 100644 --- a/control-plane/internal/services/status_manager_test.go +++ b/control-plane/internal/services/status_manager_test.go @@ -8,9 +8,9 @@ import ( "testing" "time" - "github.com/your-org/brain/control-plane/internal/core/interfaces" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/core/interfaces" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/stretchr/testify/require" ) @@ -59,8 +59,8 @@ func setupStatusManagerStorage(t *testing.T) (storage.StorageProvider, context.C cfg := storage.StorageConfig{ Mode: "local", Local: storage.LocalStorageConfig{ - DatabasePath: filepath.Join(tempDir, "brain.db"), - KVStorePath: filepath.Join(tempDir, "brain.bolt"), + DatabasePath: filepath.Join(tempDir, "haxen.db"), + KVStorePath: filepath.Join(tempDir, "haxen.bolt"), }, } diff --git a/control-plane/internal/services/ui_service.go b/control-plane/internal/services/ui_service.go index cca1429d..aeff917d 100644 --- a/control-plane/internal/services/ui_service.go +++ b/control-plane/internal/services/ui_service.go @@ -1,12 +1,12 @@ package services import ( - "github.com/your-org/brain/control-plane/internal/core/domain" - "github.com/your-org/brain/control-plane/internal/core/interfaces" - "github.com/your-org/brain/control-plane/internal/events" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/core/domain" + "github.com/your-org/haxen/control-plane/internal/core/interfaces" + "github.com/your-org/haxen/control-plane/internal/events" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" "context" "encoding/json" "fmt" diff --git a/control-plane/internal/services/vc_service.go b/control-plane/internal/services/vc_service.go index 5f336fa0..15189ef9 100644 --- a/control-plane/internal/services/vc_service.go +++ b/control-plane/internal/services/vc_service.go @@ -10,10 +10,10 @@ import ( "strings" "time" - "github.com/your-org/brain/control-plane/internal/config" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/config" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" ) // VCService handles verifiable credential generation, verification, and management. @@ -339,7 +339,7 @@ func (s *VCService) createVCDocument(ctx *types.ExecutionContext, callerIdentity InputDataHash: inputHash, OutputDataHash: outputHash, Metadata: map[string]interface{}{ - "brain_version": "1.0.0", + "haxen_version": "1.0.0", "vc_version": "1.0", }, }, @@ -352,13 +352,13 @@ func (s *VCService) createVCDocument(ctx *types.ExecutionContext, callerIdentity return &types.VCDocument{ Context: []string{ "https://www.w3.org/2018/credentials/v1", - "https://brain.example.com/contexts/execution/v1", + "https://haxen.example.com/contexts/execution/v1", }, Type: []string{ "VerifiableCredential", - "BrainExecutionCredential", + "HaxenExecutionCredential", }, - ID: fmt.Sprintf("urn:brain:vc:%s", vcID), + ID: fmt.Sprintf("urn:haxen:vc:%s", vcID), Issuer: ctx.CallerDID, IssuanceDate: time.Now().UTC().Format(time.RFC3339), CredentialSubject: credentialSubject, @@ -498,15 +498,15 @@ func (s *VCService) generateWorkflowVCDocument(workflowID string, executionVCs [ startTime = time.Now() } - // Get brain server DID as issuer using dynamic resolution - brainServerID, err := s.didService.GetBrainServerID() + // Get haxen server DID as issuer using dynamic resolution + haxenServerID, err := s.didService.GetHaxenServerID() if err != nil { - return nil, fmt.Errorf("failed to get brain server ID: %w", err) + return nil, fmt.Errorf("failed to get haxen server ID: %w", err) } - registry, err := s.didService.GetRegistry(brainServerID) + registry, err := s.didService.GetRegistry(haxenServerID) if err != nil { - return nil, fmt.Errorf("failed to get brain server DID: %w", err) + return nil, fmt.Errorf("failed to get haxen server DID: %w", err) } issuerDID := registry.RootDID @@ -581,14 +581,14 @@ func (s *VCService) createWorkflowVCDocument(workflowID, sessionID string, compo SnapshotTime: time.Now().UTC().Format(time.RFC3339), Orchestrator: types.VCCaller{ DID: issuerDID, - Type: "brain_server", + Type: "haxen_server", AgentNodeDID: issuerDID, }, Audit: types.VCAudit{ InputDataHash: "", // Workflow-level doesn't have specific input/output OutputDataHash: "", Metadata: map[string]interface{}{ - "brain_version": "1.0.0", + "haxen_version": "1.0.0", "vc_version": "1.0", "workflow_type": "agent_execution_chain", "total_executions": len(componentVCIDs), @@ -604,13 +604,13 @@ func (s *VCService) createWorkflowVCDocument(workflowID, sessionID string, compo return &types.WorkflowVCDocument{ Context: []string{ "https://www.w3.org/2018/credentials/v1", - "https://brain.example.com/contexts/workflow/v1", + "https://haxen.example.com/contexts/workflow/v1", }, Type: []string{ "VerifiableCredential", - "BrainWorkflowCredential", + "HaxenWorkflowCredential", }, - ID: fmt.Sprintf("urn:brain:workflow-vc:%s", vcID), + ID: fmt.Sprintf("urn:haxen:workflow-vc:%s", vcID), Issuer: issuerDID, IssuanceDate: time.Now().UTC().Format(time.RFC3339), CredentialSubject: credentialSubject, @@ -851,7 +851,7 @@ type SecurityAnalysis struct { // ComplianceChecks represents compliance and audit verification results type ComplianceChecks struct { W3CCompliance bool `json:"w3c_compliance"` - BrainStandardCompliance bool `json:"brain_standard_compliance"` + HaxenStandardCompliance bool `json:"haxen_standard_compliance"` AuditTrailIntegrity bool `json:"audit_trail_integrity"` DataIntegrityChecks bool `json:"data_integrity_checks"` Issues []VerificationIssue `json:"issues"` @@ -1034,7 +1034,7 @@ func (s *VCService) performIntegrityChecks(execVC *types.ExecutionVC, vcDoc *typ }) } - // CRITICAL CHECK 7: Status consistency (with Brain system status mapping) + // CRITICAL CHECK 7: Status consistency (with Haxen system status mapping) if !s.isStatusConsistent(execVC.Status, vcDoc.CredentialSubject.Execution.Status) { result.FieldConsistency = false result.Issues = append(result.Issues, VerificationIssue{ @@ -1171,7 +1171,7 @@ func (s *VCService) performSecurityAnalysis(execVC *types.ExecutionVC, vcDoc *ty func (s *VCService) performComplianceChecks(vcDoc *types.VCDocument) ComplianceChecks { result := ComplianceChecks{ W3CCompliance: true, - BrainStandardCompliance: true, + HaxenStandardCompliance: true, AuditTrailIntegrity: true, DataIntegrityChecks: true, Issues: []VerificationIssue{}, @@ -1188,14 +1188,14 @@ func (s *VCService) performComplianceChecks(vcDoc *types.VCDocument) ComplianceC }) } - // Check Brain standard compliance - if !s.checkBrainStandardCompliance(vcDoc) { - result.BrainStandardCompliance = false + // Check Haxen standard compliance + if !s.checkHaxenStandardCompliance(vcDoc) { + result.HaxenStandardCompliance = false result.Issues = append(result.Issues, VerificationIssue{ - Type: "brain_compliance_failure", + Type: "haxen_compliance_failure", Severity: "warning", Component: vcDoc.ID, - Description: "VC does not meet Brain standard requirements", + Description: "VC does not meet Haxen standard requirements", }) } @@ -1275,9 +1275,9 @@ func (s *VCService) checkW3CCompliance(vcDoc *types.VCDocument) bool { return true } -func (s *VCService) checkBrainStandardCompliance(vcDoc *types.VCDocument) bool { - // Check Brain-specific compliance requirements - requiredTypes := []string{"VerifiableCredential", "BrainExecutionCredential"} +func (s *VCService) checkHaxenStandardCompliance(vcDoc *types.VCDocument) bool { + // Check Haxen-specific compliance requirements + requiredTypes := []string{"VerifiableCredential", "HaxenExecutionCredential"} for _, required := range requiredTypes { found := false for _, vcType := range vcDoc.Type { @@ -1312,7 +1312,7 @@ func (s *VCService) calculateOverallScore(result *ComprehensiveVCVerificationRes return score } -// isStatusConsistent checks if status values are consistent, accounting for Brain system status mapping +// isStatusConsistent checks if status values are consistent, accounting for Haxen system status mapping func (s *VCService) isStatusConsistent(metadataStatus, vcDocStatus string) bool { return types.NormalizeExecutionStatus(metadataStatus) == types.NormalizeExecutionStatus(vcDocStatus) } @@ -1367,7 +1367,7 @@ func (s *VCService) VerifyWorkflowVCComprehensive(workflowID string) (*Comprehen allComplianceChecks := ComplianceChecks{ W3CCompliance: true, - BrainStandardCompliance: true, + HaxenStandardCompliance: true, AuditTrailIntegrity: true, DataIntegrityChecks: true, Issues: []VerificationIssue{}, @@ -1422,8 +1422,8 @@ func (s *VCService) VerifyWorkflowVCComprehensive(workflowID string) (*Comprehen if !complianceChecks.W3CCompliance { allComplianceChecks.W3CCompliance = false } - if !complianceChecks.BrainStandardCompliance { - allComplianceChecks.BrainStandardCompliance = false + if !complianceChecks.HaxenStandardCompliance { + allComplianceChecks.HaxenStandardCompliance = false } if !complianceChecks.AuditTrailIntegrity { allComplianceChecks.AuditTrailIntegrity = false @@ -1482,12 +1482,12 @@ func (s *VCService) VerifyWorkflowVCComprehensive(workflowID string) (*Comprehen // Check workflow VC compliance if !s.checkWorkflowVCCompliance(&workflowVCDoc) { - allComplianceChecks.BrainStandardCompliance = false + allComplianceChecks.HaxenStandardCompliance = false allComplianceChecks.Issues = append(allComplianceChecks.Issues, VerificationIssue{ Type: "workflow_compliance_failure", Severity: "warning", Component: vcChain.WorkflowVC.WorkflowVCID, - Description: "Workflow VC does not meet Brain standard requirements", + Description: "Workflow VC does not meet Haxen standard requirements", }) } } @@ -1559,10 +1559,10 @@ func (s *VCService) verifyWorkflowVCSignature(vcDoc *types.WorkflowVCDocument, i return ed25519.Verify(publicKey, canonicalBytes, signatureBytes), nil } -// checkWorkflowVCCompliance checks if a workflow VC meets Brain standard compliance +// checkWorkflowVCCompliance checks if a workflow VC meets Haxen standard compliance func (s *VCService) checkWorkflowVCCompliance(vcDoc *types.WorkflowVCDocument) bool { - // Check Brain-specific compliance requirements for workflow VCs - requiredTypes := []string{"VerifiableCredential", "BrainWorkflowCredential"} + // Check Haxen-specific compliance requirements for workflow VCs + requiredTypes := []string{"VerifiableCredential", "HaxenWorkflowCredential"} for _, required := range requiredTypes { found := false for _, vcType := range vcDoc.Type { diff --git a/control-plane/internal/services/vc_storage.go b/control-plane/internal/services/vc_storage.go index 218732d7..8a94c463 100644 --- a/control-plane/internal/services/vc_storage.go +++ b/control-plane/internal/services/vc_storage.go @@ -5,9 +5,9 @@ import ( "encoding/json" "fmt" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/internal/storage" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/internal/storage" + "github.com/your-org/haxen/control-plane/pkg/types" ) // VCStorage manages the storage and retrieval of verifiable credentials. diff --git a/control-plane/internal/services/webhook_dispatcher.go b/control-plane/internal/services/webhook_dispatcher.go index a9e2e556..5f30487e 100644 --- a/control-plane/internal/services/webhook_dispatcher.go +++ b/control-plane/internal/services/webhook_dispatcher.go @@ -14,8 +14,8 @@ import ( "sync" "time" - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/pkg/types" ) type WebhookStore interface { @@ -316,7 +316,7 @@ func (d *webhookDispatcher) process(job webhookJob) { req.Header.Set(trimmedKey, value) } if webhook.Secret != nil { - req.Header.Set("X-Brain-Signature", generateWebhookSignature(*webhook.Secret, body)) + req.Header.Set("X-Haxen-Signature", generateWebhookSignature(*webhook.Secret, body)) } var ( diff --git a/control-plane/internal/services/workflowstatus/aggregator.go b/control-plane/internal/services/workflowstatus/aggregator.go index 0c637595..be4ffc07 100644 --- a/control-plane/internal/services/workflowstatus/aggregator.go +++ b/control-plane/internal/services/workflowstatus/aggregator.go @@ -1,7 +1,7 @@ package workflowstatus import ( - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" "strings" "time" ) diff --git a/control-plane/internal/services/workflowstatus/aggregator_test.go b/control-plane/internal/services/workflowstatus/aggregator_test.go index bedad14e..809dea8f 100644 --- a/control-plane/internal/services/workflowstatus/aggregator_test.go +++ b/control-plane/internal/services/workflowstatus/aggregator_test.go @@ -1,7 +1,7 @@ package workflowstatus import ( - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" "testing" "time" ) diff --git a/control-plane/internal/storage/events.go b/control-plane/internal/storage/events.go index 3147c1f6..941e640c 100644 --- a/control-plane/internal/storage/events.go +++ b/control-plane/internal/storage/events.go @@ -1,7 +1,7 @@ package storage import ( - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" "context" "database/sql" "encoding/json" diff --git a/control-plane/internal/storage/execution_records.go b/control-plane/internal/storage/execution_records.go index 810a0202..7d14990c 100644 --- a/control-plane/internal/storage/execution_records.go +++ b/control-plane/internal/storage/execution_records.go @@ -1,8 +1,8 @@ package storage import ( - "github.com/your-org/brain/control-plane/internal/logger" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/logger" + "github.com/your-org/haxen/control-plane/pkg/types" "context" "database/sql" "encoding/json" diff --git a/control-plane/internal/storage/execution_state_validation.go b/control-plane/internal/storage/execution_state_validation.go index 01404675..a3746063 100644 --- a/control-plane/internal/storage/execution_state_validation.go +++ b/control-plane/internal/storage/execution_state_validation.go @@ -3,7 +3,7 @@ package storage import ( "fmt" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" ) type InvalidExecutionStateTransitionError struct { diff --git a/control-plane/internal/storage/execution_webhooks.go b/control-plane/internal/storage/execution_webhooks.go index 091852b0..4a2bf594 100644 --- a/control-plane/internal/storage/execution_webhooks.go +++ b/control-plane/internal/storage/execution_webhooks.go @@ -1,7 +1,7 @@ package storage import ( - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" "context" "database/sql" "encoding/json" diff --git a/control-plane/internal/storage/local.go b/control-plane/internal/storage/local.go index 9192711f..34b93551 100644 --- a/control-plane/internal/storage/local.go +++ b/control-plane/internal/storage/local.go @@ -7,8 +7,8 @@ import ( "encoding/json" "errors" "fmt" - "github.com/your-org/brain/control-plane/internal/events" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/events" + "github.com/your-org/haxen/control-plane/pkg/types" "log" "net/url" "os" @@ -68,7 +68,7 @@ func (e *ValidationError) Error() string { // getWorkflowExecutionByID is a helper function that retrieves a workflow execution using DBTX interface func (ls *LocalStorage) getWorkflowExecutionByID(ctx context.Context, q DBTX, executionID string) (*types.WorkflowExecution, error) { query := ` - SELECT workflow_id, execution_id, brain_request_id, run_id, session_id, actor_id, + SELECT workflow_id, execution_id, haxen_request_id, run_id, session_id, actor_id, agent_node_id, parent_workflow_id, parent_execution_id, root_workflow_id, workflow_depth, reasoner_id, input_data, output_data, input_size, output_size, status, started_at, completed_at, duration_ms, @@ -88,7 +88,7 @@ func (ls *LocalStorage) getWorkflowExecutionByID(ctx context.Context, q DBTX, ex var leaseOwner sql.NullString var leaseExpires sql.NullTime err := row.Scan( - &execution.WorkflowID, &execution.ExecutionID, &execution.BrainRequestID, + &execution.WorkflowID, &execution.ExecutionID, &execution.HaxenRequestID, &runID, &execution.SessionID, &execution.ActorID, &execution.AgentNodeID, &execution.ParentWorkflowID, &execution.ParentExecutionID, &execution.RootWorkflowID, &execution.WorkflowDepth, &execution.ReasonerID, &inputData, &outputData, @@ -518,7 +518,7 @@ func (ls *LocalStorage) initializeSQLite(ctx context.Context) error { log.Printf("📁 Initializing SQLite database at: %s", dbPath) - busyTimeout := resolveEnvInt("BRAIN_SQLITE_BUSY_TIMEOUT_MS", 60000) + busyTimeout := resolveEnvInt("HAXEN_SQLITE_BUSY_TIMEOUT_MS", 60000) if busyTimeout <= 0 { busyTimeout = 60000 } @@ -533,12 +533,12 @@ func (ls *LocalStorage) initializeSQLite(ctx context.Context) error { ls.db = newSQLDatabase(db, "local") - maxOpen := resolveEnvInt("BRAIN_SQLITE_MAX_OPEN_CONNS", 1) + maxOpen := resolveEnvInt("HAXEN_SQLITE_MAX_OPEN_CONNS", 1) if maxOpen <= 0 { maxOpen = 1 } ls.db.SetMaxOpenConns(maxOpen) - idleConns := resolveEnvInt("BRAIN_SQLITE_MAX_IDLE_CONNS", 1) + idleConns := resolveEnvInt("HAXEN_SQLITE_MAX_IDLE_CONNS", 1) if idleConns < 0 { idleConns = 0 } @@ -1122,7 +1122,7 @@ func (ls *LocalStorage) ensureSQLiteIndexes() error { "CREATE INDEX IF NOT EXISTS idx_agent_nodes_health ON agent_nodes(health_status)", "CREATE INDEX IF NOT EXISTS idx_agent_nodes_lifecycle ON agent_nodes(lifecycle_status)", "CREATE INDEX IF NOT EXISTS idx_agent_dids_agent_node ON agent_dids(agent_node_id)", - "CREATE INDEX IF NOT EXISTS idx_agent_dids_brain_server ON agent_dids(brain_server_id)", + "CREATE INDEX IF NOT EXISTS idx_agent_dids_haxen_server ON agent_dids(haxen_server_id)", "CREATE INDEX IF NOT EXISTS idx_component_dids_agent_did ON component_dids(agent_did)", "CREATE INDEX IF NOT EXISTS idx_component_dids_type ON component_dids(component_type)", "CREATE INDEX IF NOT EXISTS idx_execution_vcs_execution_id ON execution_vcs(execution_id)", @@ -1942,7 +1942,7 @@ func (ls *LocalStorage) retryDatabaseOperation(ctx context.Context, operationID // sqliteWorkflowExecutionInsertQuery captures the column order for workflow execution inserts. const sqliteWorkflowExecutionInsertQuery = `INSERT INTO workflow_executions ( - workflow_id, execution_id, brain_request_id, run_id, session_id, actor_id, + workflow_id, execution_id, haxen_request_id, run_id, session_id, actor_id, agent_node_id, parent_workflow_id, parent_execution_id, root_workflow_id, workflow_depth, reasoner_id, input_data, output_data, input_size, output_size, status, started_at, completed_at, duration_ms, @@ -2030,7 +2030,7 @@ func (ls *LocalStorage) executeWorkflowInsert(ctx context.Context, q DBTX, execu // Execute INSERT query using the DBTX interface _, err = q.ExecContext(ctx, insertQuery, - execution.WorkflowID, execution.ExecutionID, execution.BrainRequestID, execution.RunID, + execution.WorkflowID, execution.ExecutionID, execution.HaxenRequestID, execution.RunID, execution.SessionID, execution.ActorID, execution.AgentNodeID, execution.ParentWorkflowID, execution.ParentExecutionID, execution.RootWorkflowID, execution.WorkflowDepth, execution.ReasonerID, execution.InputData, execution.OutputData, @@ -2296,7 +2296,7 @@ func (ls *LocalStorage) QueryWorkflowExecutions(ctx context.Context, filters typ baseQuery := ` SELECT workflow_executions.id, workflow_executions.workflow_id, workflow_executions.execution_id, - workflow_executions.brain_request_id, workflow_executions.run_id, workflow_executions.session_id, workflow_executions.actor_id, + workflow_executions.haxen_request_id, workflow_executions.run_id, workflow_executions.session_id, workflow_executions.actor_id, workflow_executions.agent_node_id, workflow_executions.parent_workflow_id, workflow_executions.parent_execution_id, workflow_executions.root_workflow_id, workflow_executions.workflow_depth, workflow_executions.reasoner_id, workflow_executions.input_data, workflow_executions.output_data, @@ -2424,7 +2424,7 @@ func (ls *LocalStorage) QueryWorkflowExecutions(ctx context.Context, filters typ err := rows.Scan( &execution.ID, &execution.WorkflowID, &execution.ExecutionID, - &execution.BrainRequestID, &runID, &execution.SessionID, &execution.ActorID, + &execution.HaxenRequestID, &runID, &execution.SessionID, &execution.ActorID, &execution.AgentNodeID, &execution.ParentWorkflowID, &execution.ParentExecutionID, &execution.RootWorkflowID, &execution.WorkflowDepth, &execution.ReasonerID, &inputData, &outputData, &execution.InputSize, &execution.OutputSize, @@ -2498,7 +2498,7 @@ func (ls *LocalStorage) QueryWorkflowDAG(ctx context.Context, rootWorkflowID str WITH RECURSIVE workflow_dag AS ( -- Base case: Find the root execution(s) SELECT - id, workflow_id, execution_id, brain_request_id, run_id, session_id, actor_id, + id, workflow_id, execution_id, haxen_request_id, run_id, session_id, actor_id, agent_node_id, parent_workflow_id, parent_execution_id, root_workflow_id, workflow_depth, reasoner_id, input_data, output_data, input_size, output_size, status, started_at, completed_at, duration_ms, @@ -2516,7 +2516,7 @@ func (ls *LocalStorage) QueryWorkflowDAG(ctx context.Context, rootWorkflowID str -- Recursive case: Find children of current level SELECT - we.id, we.workflow_id, we.execution_id, we.brain_request_id, we.run_id, we.session_id, we.actor_id, + we.id, we.workflow_id, we.execution_id, we.haxen_request_id, we.run_id, we.session_id, we.actor_id, we.agent_node_id, we.parent_workflow_id, we.parent_execution_id, we.root_workflow_id, we.workflow_depth, we.reasoner_id, we.input_data, we.output_data, we.input_size, we.output_size, we.status, we.started_at, we.completed_at, we.duration_ms, @@ -2532,7 +2532,7 @@ func (ls *LocalStorage) QueryWorkflowDAG(ctx context.Context, rootWorkflowID str AND wd.path NOT LIKE '%' || we.execution_id || '%' -- Cycle detection ) SELECT - id, workflow_id, execution_id, brain_request_id, run_id, session_id, actor_id, + id, workflow_id, execution_id, haxen_request_id, run_id, session_id, actor_id, agent_node_id, parent_workflow_id, parent_execution_id, root_workflow_id, workflow_depth, reasoner_id, input_data, output_data, input_size, output_size, status, started_at, completed_at, duration_ms, @@ -2565,7 +2565,7 @@ func (ls *LocalStorage) QueryWorkflowDAG(ctx context.Context, rootWorkflowID str err := rows.Scan( &execution.ID, &execution.WorkflowID, &execution.ExecutionID, - &execution.BrainRequestID, &runID, &execution.SessionID, &execution.ActorID, + &execution.HaxenRequestID, &runID, &execution.SessionID, &execution.ActorID, &execution.AgentNodeID, &execution.ParentWorkflowID, &execution.ParentExecutionID, &execution.RootWorkflowID, &execution.WorkflowDepth, &execution.ReasonerID, &inputData, &outputData, &execution.InputSize, &execution.OutputSize, @@ -5337,20 +5337,20 @@ func (ls *LocalStorage) GetWorkflowExecutionEventBus() *events.EventBus[*types.W return ls.workflowExecutionEventBus } -// Brain Server DID operations -func (ls *LocalStorage) StoreBrainServerDID(ctx context.Context, brainServerID, rootDID string, masterSeed []byte, createdAt, lastKeyRotation time.Time) error { +// Haxen Server DID operations +func (ls *LocalStorage) StoreHaxenServerDID(ctx context.Context, haxenServerID, rootDID string, masterSeed []byte, createdAt, lastKeyRotation time.Time) error { // Check context cancellation early if err := ctx.Err(); err != nil { - return fmt.Errorf("context cancelled during store brain server DID: %w", err) + return fmt.Errorf("context cancelled during store haxen server DID: %w", err) } // Validate input parameters - if brainServerID == "" { + if haxenServerID == "" { return &ValidationError{ - Field: "brain_server_id", - Value: brainServerID, - Reason: "brain server ID cannot be empty", - Context: "StoreBrainServerDID", + Field: "haxen_server_id", + Value: haxenServerID, + Reason: "haxen server ID cannot be empty", + Context: "StoreHaxenServerDID", } } if rootDID == "" { @@ -5358,7 +5358,7 @@ func (ls *LocalStorage) StoreBrainServerDID(ctx context.Context, brainServerID, Field: "root_did", Value: rootDID, Reason: "root DID cannot be empty", - Context: "StoreBrainServerDID", + Context: "StoreHaxenServerDID", } } if len(masterSeed) == 0 { @@ -5366,7 +5366,7 @@ func (ls *LocalStorage) StoreBrainServerDID(ctx context.Context, brainServerID, Field: "master_seed", Value: "", Reason: "master seed cannot be empty", - Context: "StoreBrainServerDID", + Context: "StoreHaxenServerDID", } } @@ -5384,14 +5384,14 @@ func (ls *LocalStorage) StoreBrainServerDID(ctx context.Context, brainServerID, // Execute with retry logic err = ls.retryOnConstraintFailure(ctx, func() error { query := ` - INSERT OR REPLACE INTO did_registry (brain_server_id, root_did, master_seed_encrypted, created_at, last_key_rotation, total_dids) + INSERT OR REPLACE INTO did_registry (haxen_server_id, root_did, master_seed_encrypted, created_at, last_key_rotation, total_dids) VALUES (?, ?, ?, ?, ?, 0) ` if ls.mode == "postgres" { query = ` - INSERT INTO did_registry (brain_server_id, root_did, master_seed_encrypted, created_at, last_key_rotation, total_dids) + INSERT INTO did_registry (haxen_server_id, root_did, master_seed_encrypted, created_at, last_key_rotation, total_dids) VALUES (?, ?, ?, ?, ?, 0) - ON CONFLICT (brain_server_id) DO UPDATE SET + ON CONFLICT (haxen_server_id) DO UPDATE SET root_did = EXCLUDED.root_did, master_seed_encrypted = EXCLUDED.master_seed_encrypted, created_at = EXCLUDED.created_at, @@ -5399,9 +5399,9 @@ func (ls *LocalStorage) StoreBrainServerDID(ctx context.Context, brainServerID, total_dids = did_registry.total_dids ` } - _, execErr := tx.ExecContext(ctx, query, brainServerID, rootDID, masterSeed, createdAt, lastKeyRotation) + _, execErr := tx.ExecContext(ctx, query, haxenServerID, rootDID, masterSeed, createdAt, lastKeyRotation) if execErr != nil { - return fmt.Errorf("failed to store brain server DID: %w", execErr) + return fmt.Errorf("failed to store haxen server DID: %w", execErr) } return nil }, 3) // Retry up to 3 times for transient errors @@ -5415,19 +5415,19 @@ func (ls *LocalStorage) StoreBrainServerDID(ctx context.Context, brainServerID, return fmt.Errorf("failed to commit transaction: %w", err) } - log.Printf("Successfully stored brain server DID: brain_server_id=%s, root_did=%s", brainServerID, rootDID) + log.Printf("Successfully stored haxen server DID: haxen_server_id=%s, root_did=%s", haxenServerID, rootDID) return nil } // StoreAgentDIDWithComponents stores an agent DID along with its component DIDs in a single transaction -func (ls *LocalStorage) StoreAgentDIDWithComponents(ctx context.Context, agentID, agentDID, brainServerDID, publicKeyJWK string, derivationIndex int, components []ComponentDIDRequest) error { +func (ls *LocalStorage) StoreAgentDIDWithComponents(ctx context.Context, agentID, agentDID, haxenServerDID, publicKeyJWK string, derivationIndex int, components []ComponentDIDRequest) error { // Check context cancellation early if err := ctx.Err(); err != nil { return fmt.Errorf("context cancelled during store agent DID with components: %w", err) } // Pre-storage validation - if err := ls.validateBrainServerExists(ctx, brainServerDID); err != nil { + if err := ls.validateHaxenServerExists(ctx, haxenServerDID); err != nil { return fmt.Errorf("pre-storage validation failed: %w", err) } @@ -5446,24 +5446,24 @@ func (ls *LocalStorage) StoreAgentDIDWithComponents(ctx context.Context, agentID err = ls.retryOnConstraintFailure(ctx, func() error { query := ` INSERT INTO agent_dids ( - agent_node_id, did, brain_server_id, public_key_jwk, derivation_path, registered_at, status + agent_node_id, did, haxen_server_id, public_key_jwk, derivation_path, registered_at, status ) VALUES (?, ?, ?, ?, ?, ?, ?)` derivationPath := fmt.Sprintf("m/44'/0'/0'/%d", derivationIndex) - _, execErr := tx.ExecContext(ctx, query, agentID, agentDID, brainServerDID, publicKeyJWK, derivationPath, time.Now(), "active") + _, execErr := tx.ExecContext(ctx, query, agentID, agentDID, haxenServerDID, publicKeyJWK, derivationPath, time.Now(), "active") if execErr != nil { if strings.Contains(execErr.Error(), "UNIQUE constraint failed") || strings.Contains(execErr.Error(), "agent_dids") { return &DuplicateDIDError{ - DID: fmt.Sprintf("agent:%s@%s", agentID, brainServerDID), + DID: fmt.Sprintf("agent:%s@%s", agentID, haxenServerDID), Type: "agent", } } if strings.Contains(execErr.Error(), "FOREIGN KEY constraint failed") { return &ForeignKeyConstraintError{ Table: "agent_dids", - Column: "brain_server_id", + Column: "haxen_server_id", ReferencedTable: "did_registry", - ReferencedValue: brainServerDID, + ReferencedValue: haxenServerDID, Operation: "INSERT", } } @@ -5521,56 +5521,56 @@ func (ls *LocalStorage) StoreAgentDIDWithComponents(ctx context.Context, agentID return nil } -func (ls *LocalStorage) GetBrainServerDID(ctx context.Context, brainServerID string) (*types.BrainServerDIDInfo, error) { +func (ls *LocalStorage) GetHaxenServerDID(ctx context.Context, haxenServerID string) (*types.HaxenServerDIDInfo, error) { // Check context cancellation early if err := ctx.Err(); err != nil { - return nil, fmt.Errorf("context cancelled during get brain server DID: %w", err) + return nil, fmt.Errorf("context cancelled during get haxen server DID: %w", err) } query := ` - SELECT brain_server_id, root_did, master_seed_encrypted, created_at, last_key_rotation - FROM did_registry WHERE brain_server_id = ? + SELECT haxen_server_id, root_did, master_seed_encrypted, created_at, last_key_rotation + FROM did_registry WHERE haxen_server_id = ? ` - row := ls.db.QueryRowContext(ctx, query, brainServerID) - info := &types.BrainServerDIDInfo{} + row := ls.db.QueryRowContext(ctx, query, haxenServerID) + info := &types.HaxenServerDIDInfo{} - err := row.Scan(&info.BrainServerID, &info.RootDID, &info.MasterSeed, &info.CreatedAt, &info.LastKeyRotation) + err := row.Scan(&info.HaxenServerID, &info.RootDID, &info.MasterSeed, &info.CreatedAt, &info.LastKeyRotation) if err != nil { if err == sql.ErrNoRows { return nil, nil // Return nil, nil for "not found" } - return nil, fmt.Errorf("failed to get brain server DID: %w", err) + return nil, fmt.Errorf("failed to get haxen server DID: %w", err) } return info, nil } -func (ls *LocalStorage) ListBrainServerDIDs(ctx context.Context) ([]*types.BrainServerDIDInfo, error) { +func (ls *LocalStorage) ListHaxenServerDIDs(ctx context.Context) ([]*types.HaxenServerDIDInfo, error) { // Check context cancellation early if err := ctx.Err(); err != nil { - return nil, fmt.Errorf("context cancelled during list brain server DIDs: %w", err) + return nil, fmt.Errorf("context cancelled during list haxen server DIDs: %w", err) } query := ` - SELECT brain_server_id, root_did, master_seed_encrypted, created_at, last_key_rotation + SELECT haxen_server_id, root_did, master_seed_encrypted, created_at, last_key_rotation FROM did_registry ORDER BY created_at DESC ` rows, err := ls.db.QueryContext(ctx, query) if err != nil { - return nil, fmt.Errorf("failed to list brain server DIDs: %w", err) + return nil, fmt.Errorf("failed to list haxen server DIDs: %w", err) } defer rows.Close() - var infos []*types.BrainServerDIDInfo + var infos []*types.HaxenServerDIDInfo for rows.Next() { // Check context cancellation during iteration if err := ctx.Err(); err != nil { - return nil, fmt.Errorf("context cancelled during brain server DID list iteration: %w", err) + return nil, fmt.Errorf("context cancelled during haxen server DID list iteration: %w", err) } - info := &types.BrainServerDIDInfo{} - err := rows.Scan(&info.BrainServerID, &info.RootDID, &info.MasterSeed, &info.CreatedAt, &info.LastKeyRotation) + info := &types.HaxenServerDIDInfo{} + err := rows.Scan(&info.HaxenServerID, &info.RootDID, &info.MasterSeed, &info.CreatedAt, &info.LastKeyRotation) if err != nil { - return nil, fmt.Errorf("failed to scan brain server DID: %w", err) + return nil, fmt.Errorf("failed to scan haxen server DID: %w", err) } infos = append(infos, info) } @@ -5669,31 +5669,31 @@ func (ls *LocalStorage) ListDIDs(ctx context.Context) ([]*types.DIDRegistryEntry return entries, nil } -// validateBrainServerExists checks if a brain server registry exists -func (ls *LocalStorage) validateBrainServerExists(ctx context.Context, brainServerID string) error { - if brainServerID == "" { +// validateHaxenServerExists checks if a haxen server registry exists +func (ls *LocalStorage) validateHaxenServerExists(ctx context.Context, haxenServerID string) error { + if haxenServerID == "" { return &ValidationError{ - Field: "brain_server_id", - Value: brainServerID, - Reason: "brain server ID cannot be empty", + Field: "haxen_server_id", + Value: haxenServerID, + Reason: "haxen server ID cannot be empty", Context: "pre-storage validation", } } - query := `SELECT 1 FROM did_registry WHERE brain_server_id = ? LIMIT 1` + query := `SELECT 1 FROM did_registry WHERE haxen_server_id = ? LIMIT 1` var exists int - err := ls.db.QueryRowContext(ctx, query, brainServerID).Scan(&exists) + err := ls.db.QueryRowContext(ctx, query, haxenServerID).Scan(&exists) if err != nil { if err == sql.ErrNoRows { return &ForeignKeyConstraintError{ Table: "agent_dids", - Column: "brain_server_id", + Column: "haxen_server_id", ReferencedTable: "did_registry", - ReferencedValue: brainServerID, + ReferencedValue: haxenServerID, Operation: "INSERT", } } - return fmt.Errorf("failed to validate brain server existence: %w", err) + return fmt.Errorf("failed to validate haxen server existence: %w", err) } return nil } @@ -5770,14 +5770,14 @@ func (ls *LocalStorage) retryOnConstraintFailure(ctx context.Context, operation } // Agent DID operations -func (ls *LocalStorage) StoreAgentDID(ctx context.Context, agentID, agentDID, brainServerDID, publicKeyJWK string, derivationIndex int) error { +func (ls *LocalStorage) StoreAgentDID(ctx context.Context, agentID, agentDID, haxenServerDID, publicKeyJWK string, derivationIndex int) error { // Check context cancellation early if err := ctx.Err(); err != nil { return fmt.Errorf("context cancelled during store agent DID: %w", err) } // Pre-storage validation - if err := ls.validateBrainServerExists(ctx, brainServerDID); err != nil { + if err := ls.validateHaxenServerExists(ctx, haxenServerDID); err != nil { return fmt.Errorf("pre-storage validation failed: %w", err) } @@ -5823,17 +5823,17 @@ func (ls *LocalStorage) StoreAgentDID(ctx context.Context, agentID, agentDID, br // INSERT-only query - no ON CONFLICT clause for security query := ` INSERT INTO agent_dids ( - agent_node_id, did, brain_server_id, public_key_jwk, derivation_path, registered_at, status + agent_node_id, did, haxen_server_id, public_key_jwk, derivation_path, registered_at, status ) VALUES (?, ?, ?, ?, ?, ?, ?)` derivationPath := fmt.Sprintf("m/44'/0'/0'/%d", derivationIndex) - _, execErr := tx.ExecContext(ctx, query, agentID, agentDID, brainServerDID, publicKeyJWK, derivationPath, time.Now(), "active") + _, execErr := tx.ExecContext(ctx, query, agentID, agentDID, haxenServerDID, publicKeyJWK, derivationPath, time.Now(), "active") if execErr != nil { // Check if this is a unique constraint violation (duplicate agent DID) if strings.Contains(execErr.Error(), "UNIQUE constraint failed") || strings.Contains(execErr.Error(), "agent_dids") { - log.Printf("Duplicate agent DID entry detected: agent_id=%s, brain_server_id=%s", agentID, brainServerDID) + log.Printf("Duplicate agent DID entry detected: agent_id=%s, haxen_server_id=%s", agentID, haxenServerDID) return &DuplicateDIDError{ - DID: fmt.Sprintf("agent:%s@%s", agentID, brainServerDID), + DID: fmt.Sprintf("agent:%s@%s", agentID, haxenServerDID), Type: "agent", } } @@ -5841,9 +5841,9 @@ func (ls *LocalStorage) StoreAgentDID(ctx context.Context, agentID, agentDID, br if strings.Contains(execErr.Error(), "FOREIGN KEY constraint failed") { return &ForeignKeyConstraintError{ Table: "agent_dids", - Column: "brain_server_id", + Column: "haxen_server_id", ReferencedTable: "did_registry", - ReferencedValue: brainServerDID, + ReferencedValue: haxenServerDID, Operation: "INSERT", } } @@ -5872,7 +5872,7 @@ func (ls *LocalStorage) GetAgentDID(ctx context.Context, agentID string) (*types } query := ` - SELECT agent_node_id, did, brain_server_id, public_key_jwk, derivation_path, + SELECT agent_node_id, did, haxen_server_id, public_key_jwk, derivation_path, reasoners, skills, status, registered_at FROM agent_dids WHERE agent_node_id = ?` @@ -5880,7 +5880,7 @@ func (ls *LocalStorage) GetAgentDID(ctx context.Context, agentID string) (*types info := &types.AgentDIDInfo{} var reasonersJSON, skillsJSON, publicKeyJWK string - err := row.Scan(&info.AgentNodeID, &info.DID, &info.BrainServerID, &publicKeyJWK, + err := row.Scan(&info.AgentNodeID, &info.DID, &info.HaxenServerID, &publicKeyJWK, &info.DerivationPath, &reasonersJSON, &skillsJSON, &info.Status, &info.RegisteredAt) if err != nil { if err == sql.ErrNoRows { @@ -5917,7 +5917,7 @@ func (ls *LocalStorage) ListAgentDIDs(ctx context.Context) ([]*types.AgentDIDInf } query := ` - SELECT agent_node_id, did, brain_server_id, public_key_jwk, derivation_path, + SELECT agent_node_id, did, haxen_server_id, public_key_jwk, derivation_path, reasoners, skills, status, registered_at FROM agent_dids ORDER BY registered_at DESC` @@ -5936,7 +5936,7 @@ func (ls *LocalStorage) ListAgentDIDs(ctx context.Context) ([]*types.AgentDIDInf info := &types.AgentDIDInfo{} var reasonersJSON, skillsJSON, publicKeyJWK string - err := rows.Scan(&info.AgentNodeID, &info.DID, &info.BrainServerID, &publicKeyJWK, + err := rows.Scan(&info.AgentNodeID, &info.DID, &info.HaxenServerID, &publicKeyJWK, &info.DerivationPath, &reasonersJSON, &skillsJSON, &info.Status, &info.RegisteredAt) if err != nil { return nil, fmt.Errorf("failed to scan agent DID: %w", err) diff --git a/control-plane/internal/storage/local_agent_execution_test.go b/control-plane/internal/storage/local_agent_execution_test.go index ea88f138..07e001e0 100644 --- a/control-plane/internal/storage/local_agent_execution_test.go +++ b/control-plane/internal/storage/local_agent_execution_test.go @@ -6,7 +6,7 @@ import ( "testing" "time" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/stretchr/testify/require" ) diff --git a/control-plane/internal/storage/local_cleanup_test.go b/control-plane/internal/storage/local_cleanup_test.go index d2148534..5f278890 100644 --- a/control-plane/internal/storage/local_cleanup_test.go +++ b/control-plane/internal/storage/local_cleanup_test.go @@ -8,7 +8,7 @@ import ( "testing" "time" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/stretchr/testify/require" ) @@ -20,8 +20,8 @@ func TestLocalStorageCleanupWorkflowByRunID(t *testing.T) { cfg := StorageConfig{ Mode: "local", Local: LocalStorageConfig{ - DatabasePath: filepath.Join(tempDir, "brain.db"), - KVStorePath: filepath.Join(tempDir, "brain.bolt"), + DatabasePath: filepath.Join(tempDir, "haxen.db"), + KVStorePath: filepath.Join(tempDir, "haxen.bolt"), }, } @@ -69,7 +69,7 @@ func TestLocalStorageCleanupWorkflowByRunID(t *testing.T) { exec := &types.WorkflowExecution{ WorkflowID: workflowID, ExecutionID: "exec_cleanup_test", - BrainRequestID: "req_cleanup_test", + HaxenRequestID: "req_cleanup_test", RunID: &runID, AgentNodeID: "agent_cleanup", ReasonerID: "reasoner.cleanup", @@ -157,8 +157,8 @@ func TestLocalStorageCleanupOldExecutions(t *testing.T) { cfg := StorageConfig{ Mode: "local", Local: LocalStorageConfig{ - DatabasePath: filepath.Join(tempDir, "brain.db"), - KVStorePath: filepath.Join(tempDir, "brain.bolt"), + DatabasePath: filepath.Join(tempDir, "haxen.db"), + KVStorePath: filepath.Join(tempDir, "haxen.bolt"), }, } @@ -181,7 +181,7 @@ func TestLocalStorageCleanupOldExecutions(t *testing.T) { exec := &types.WorkflowExecution{ WorkflowID: workflowID, ExecutionID: executionID, - BrainRequestID: executionID + "_req", + HaxenRequestID: executionID + "_req", AgentNodeID: "agent", ReasonerID: "reasoner", Status: "completed", diff --git a/control-plane/internal/storage/local_query_test.go b/control-plane/internal/storage/local_query_test.go index 4c01447a..14d21fa0 100644 --- a/control-plane/internal/storage/local_query_test.go +++ b/control-plane/internal/storage/local_query_test.go @@ -7,7 +7,7 @@ import ( "testing" "time" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" "github.com/stretchr/testify/require" ) @@ -20,8 +20,8 @@ func setupLocalStorage(t *testing.T) (*LocalStorage, context.Context) { cfg := StorageConfig{ Mode: "local", Local: LocalStorageConfig{ - DatabasePath: filepath.Join(tempDir, "brain.db"), - KVStorePath: filepath.Join(tempDir, "brain.bolt"), + DatabasePath: filepath.Join(tempDir, "haxen.db"), + KVStorePath: filepath.Join(tempDir, "haxen.bolt"), }, } @@ -67,7 +67,7 @@ func TestQueryWorkflowExecutionsFiltersAndSearch(t *testing.T) { { WorkflowID: "wf-root", ExecutionID: "exec-alpha", - BrainRequestID: "req-1", + HaxenRequestID: "req-1", RunID: &runID, AgentNodeID: "agent-one", ReasonerID: "reasoner.alpha", @@ -81,7 +81,7 @@ func TestQueryWorkflowExecutionsFiltersAndSearch(t *testing.T) { { WorkflowID: "wf-root", ExecutionID: "exec-beta", - BrainRequestID: "req-2", + HaxenRequestID: "req-2", RunID: &runID, AgentNodeID: "agent-two", ReasonerID: "reasoner.beta", @@ -157,7 +157,7 @@ func TestQueryWorkflowDAGReturnsHierarchy(t *testing.T) { root := &types.WorkflowExecution{ WorkflowID: "wf-root", ExecutionID: "root-exec", - BrainRequestID: "req-root", + HaxenRequestID: "req-root", RunID: &runID, AgentNodeID: "agent-root", ReasonerID: "root", @@ -172,7 +172,7 @@ func TestQueryWorkflowDAGReturnsHierarchy(t *testing.T) { child := &types.WorkflowExecution{ WorkflowID: "wf-root", ExecutionID: "child-exec", - BrainRequestID: "req-child", + HaxenRequestID: "req-child", RunID: &runID, AgentNodeID: "agent-child", ReasonerID: "child", diff --git a/control-plane/internal/storage/local_storage_test.go b/control-plane/internal/storage/local_storage_test.go index 2e886253..6b699dff 100644 --- a/control-plane/internal/storage/local_storage_test.go +++ b/control-plane/internal/storage/local_storage_test.go @@ -7,7 +7,7 @@ import ( "testing" "time" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" ) func TestLocalStorageStoreWorkflowExecutionPersistsLifecycleFields(t *testing.T) { @@ -17,8 +17,8 @@ func TestLocalStorageStoreWorkflowExecutionPersistsLifecycleFields(t *testing.T) cfg := StorageConfig{ Mode: "local", Local: LocalStorageConfig{ - DatabasePath: filepath.Join(tempDir, "brain.db"), - KVStorePath: filepath.Join(tempDir, "brain.bolt"), + DatabasePath: filepath.Join(tempDir, "haxen.db"), + KVStorePath: filepath.Join(tempDir, "haxen.bolt"), }, } @@ -50,14 +50,14 @@ func TestLocalStorageStoreWorkflowExecutionPersistsLifecycleFields(t *testing.T) } execID := "exec_test" - brainRequestID := "req_test" + haxenRequestID := "req_test" agentID := "agent_1" reasonerID := "reasoner.alpha" exec := &types.WorkflowExecution{ WorkflowID: workflowID, ExecutionID: execID, - BrainRequestID: brainRequestID, + HaxenRequestID: haxenRequestID, RunID: &runID, AgentNodeID: agentID, ReasonerID: reasonerID, diff --git a/control-plane/internal/storage/locks.go b/control-plane/internal/storage/locks.go index 670c76ec..09b1297c 100644 --- a/control-plane/internal/storage/locks.go +++ b/control-plane/internal/storage/locks.go @@ -1,7 +1,7 @@ package storage import ( - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" "context" "database/sql" "fmt" diff --git a/control-plane/internal/storage/models.go b/control-plane/internal/storage/models.go index 827cf753..328a21cf 100644 --- a/control-plane/internal/storage/models.go +++ b/control-plane/internal/storage/models.go @@ -106,7 +106,7 @@ type WorkflowExecutionModel struct { ID int64 `gorm:"column:id;primaryKey;autoIncrement"` WorkflowID string `gorm:"column:workflow_id;not null;index;index:idx_workflow_executions_workflow_status,priority:1"` ExecutionID string `gorm:"column:execution_id;not null;uniqueIndex"` - BrainRequestID string `gorm:"column:brain_request_id;not null;index"` + HaxenRequestID string `gorm:"column:haxen_request_id;not null;index"` RunID *string `gorm:"column:run_id;index"` SessionID *string `gorm:"column:session_id;index;index:idx_workflow_executions_session_status,priority:1;index:idx_workflow_executions_session_status_time,priority:1;index:idx_workflow_executions_session_time,priority:1"` ActorID *string `gorm:"column:actor_id;index;index:idx_workflow_executions_actor_status,priority:1;index:idx_workflow_executions_actor_status_time,priority:1;index:idx_workflow_executions_actor_time,priority:1"` @@ -260,7 +260,7 @@ type SessionModel struct { func (SessionModel) TableName() string { return "sessions" } type DIDRegistryModel struct { - BrainServerID string `gorm:"column:brain_server_id;primaryKey"` + HaxenServerID string `gorm:"column:haxen_server_id;primaryKey"` MasterSeedEncrypted []byte `gorm:"column:master_seed_encrypted;not null"` RootDID string `gorm:"column:root_did;not null;unique"` AgentNodes string `gorm:"column:agent_nodes;default:'{}'"` @@ -274,7 +274,7 @@ func (DIDRegistryModel) TableName() string { return "did_registry" } type AgentDIDModel struct { DID string `gorm:"column:did;primaryKey"` AgentNodeID string `gorm:"column:agent_node_id;not null;index"` - BrainServerID string `gorm:"column:brain_server_id;not null;index"` + HaxenServerID string `gorm:"column:haxen_server_id;not null;index"` PublicKeyJWK string `gorm:"column:public_key_jwk;not null"` DerivationPath string `gorm:"column:derivation_path;not null"` Reasoners string `gorm:"column:reasoners;default:'{}'"` diff --git a/control-plane/internal/storage/storage.go b/control-plane/internal/storage/storage.go index a39f52c0..40cf8722 100644 --- a/control-plane/internal/storage/storage.go +++ b/control-plane/internal/storage/storage.go @@ -1,8 +1,8 @@ package storage import ( - "github.com/your-org/brain/control-plane/internal/events" - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/internal/events" + "github.com/your-org/haxen/control-plane/pkg/types" "context" "fmt" "os" @@ -124,13 +124,13 @@ type StorageProvider interface { GetDID(ctx context.Context, did string) (*types.DIDRegistryEntry, error) ListDIDs(ctx context.Context) ([]*types.DIDRegistryEntry, error) - // Brain Server DID operations - StoreBrainServerDID(ctx context.Context, brainServerID, rootDID string, masterSeed []byte, createdAt, lastKeyRotation time.Time) error - GetBrainServerDID(ctx context.Context, brainServerID string) (*types.BrainServerDIDInfo, error) - ListBrainServerDIDs(ctx context.Context) ([]*types.BrainServerDIDInfo, error) + // Haxen Server DID operations + StoreHaxenServerDID(ctx context.Context, haxenServerID, rootDID string, masterSeed []byte, createdAt, lastKeyRotation time.Time) error + GetHaxenServerDID(ctx context.Context, haxenServerID string) (*types.HaxenServerDIDInfo, error) + ListHaxenServerDIDs(ctx context.Context) ([]*types.HaxenServerDIDInfo, error) // Agent DID operations - StoreAgentDID(ctx context.Context, agentID, agentDID, brainServerDID, publicKeyJWK string, derivationIndex int) error + StoreAgentDID(ctx context.Context, agentID, agentDID, haxenServerDID, publicKeyJWK string, derivationIndex int) error GetAgentDID(ctx context.Context, agentID string) (*types.AgentDIDInfo, error) ListAgentDIDs(ctx context.Context) ([]*types.AgentDIDInfo, error) @@ -140,7 +140,7 @@ type StorageProvider interface { ListComponentDIDs(ctx context.Context, agentDID string) ([]*types.ComponentDIDInfo, error) // Multi-step DID operations with transaction safety - StoreAgentDIDWithComponents(ctx context.Context, agentID, agentDID, brainServerDID, publicKeyJWK string, derivationIndex int, components []ComponentDIDRequest) error + StoreAgentDIDWithComponents(ctx context.Context, agentID, agentDID, haxenServerDID, publicKeyJWK string, derivationIndex int, components []ComponentDIDRequest) error // Execution VC operations StoreExecutionVC(ctx context.Context, vcID, executionID, workflowID, sessionID, issuerDID, targetDID, callerDID, inputHash, outputHash, status string, vcDocument []byte, signature string, storageURI string, documentSizeBytes int64) error @@ -226,7 +226,7 @@ func (sf *StorageFactory) CreateStorage(config StorageConfig) (StorageProvider, } // Allow environment variable to override mode - if envMode := os.Getenv("BRAIN_STORAGE_MODE"); envMode != "" { + if envMode := os.Getenv("HAXEN_STORAGE_MODE"); envMode != "" { mode = envMode } diff --git a/control-plane/internal/storage/unitofwork.go b/control-plane/internal/storage/unitofwork.go index 5057ac09..76ba0195 100644 --- a/control-plane/internal/storage/unitofwork.go +++ b/control-plane/internal/storage/unitofwork.go @@ -1,7 +1,7 @@ package storage import ( - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" "context" "fmt" "strings" diff --git a/control-plane/internal/storage/unitofwork_test.go b/control-plane/internal/storage/unitofwork_test.go index 6499f91f..d553d183 100644 --- a/control-plane/internal/storage/unitofwork_test.go +++ b/control-plane/internal/storage/unitofwork_test.go @@ -4,7 +4,7 @@ package storage import ( - "github.com/your-org/brain/control-plane/pkg/types" + "github.com/your-org/haxen/control-plane/pkg/types" "context" // Add context import "encoding/json" "os" @@ -122,7 +122,7 @@ func TestWorkflowUnitOfWork_AtomicWorkflowExecution(t *testing.T) { execution := &types.WorkflowExecution{ WorkflowID: "test-workflow-001", ExecutionID: "test-execution-001", - BrainRequestID: "test-request-001", + HaxenRequestID: "test-request-001", SessionID: ptrString("test-session-001"), ActorID: ptrString("test-actor-001"), AgentNodeID: "test-agent-001", @@ -240,7 +240,7 @@ func TestWorkflowUnitOfWork_UpdateWorkflowStatus(t *testing.T) { execution := &types.WorkflowExecution{ WorkflowID: "test-workflow-002", ExecutionID: "test-execution-002", - BrainRequestID: "test-request-002", + HaxenRequestID: "test-request-002", AgentNodeID: "test-agent-002", ReasonerID: "test-reasoner", InputData: json.RawMessage(`{"test": "input"}`), diff --git a/control-plane/internal/storage/workflow_execution_queries_test.go b/control-plane/internal/storage/workflow_execution_queries_test.go index 9d7ed3db..ad375a80 100644 --- a/control-plane/internal/storage/workflow_execution_queries_test.go +++ b/control-plane/internal/storage/workflow_execution_queries_test.go @@ -8,7 +8,7 @@ import ( var workflowExecutionLifecycleColumns = []string{ "workflow_id", "execution_id", - "brain_request_id", + "haxen_request_id", "run_id", "session_id", "actor_id", diff --git a/control-plane/internal/templates/agent/.env.example.tmpl b/control-plane/internal/templates/agent/.env.example.tmpl index 8147a188..5254a96a 100644 --- a/control-plane/internal/templates/agent/.env.example.tmpl +++ b/control-plane/internal/templates/agent/.env.example.tmpl @@ -6,4 +6,4 @@ # ANTHROPIC_API_KEY=... # OPENROUTER_API_KEY=... -# brain run will inject BRAIN_SERVER_URL, LOG_LEVEL, and PORT automatically. +# haxen run will inject HAXEN_SERVER_URL, LOG_LEVEL, and PORT automatically. diff --git a/control-plane/internal/templates/agent/.gitignore.tmpl b/control-plane/internal/templates/agent/.gitignore.tmpl index f55279ae..32c54d43 100644 --- a/control-plane/internal/templates/agent/.gitignore.tmpl +++ b/control-plane/internal/templates/agent/.gitignore.tmpl @@ -1,4 +1,4 @@ -# Brain Agent Project - {{.ProjectName}} +# Haxen Agent Project - {{.ProjectName}} # Generated on {{.CreatedAt}} # Python @@ -73,11 +73,11 @@ venv.bak/ ehthumbs.db Thumbs.db -# Brain specific -brain_local.db -brain_local.db-shm -brain_local.db-wal -brain_local.bolt +# Haxen specific +haxen_local.db +haxen_local.db-shm +haxen_local.db-wal +haxen_local.bolt *.log # Local configuration diff --git a/control-plane/internal/templates/agent/README.md.tmpl b/control-plane/internal/templates/agent/README.md.tmpl index d005efb5..00255726 100644 --- a/control-plane/internal/templates/agent/README.md.tmpl +++ b/control-plane/internal/templates/agent/README.md.tmpl @@ -1,24 +1,24 @@ # {{.ProjectName}} -Minimal Brain agent scaffold generated on {{.CreatedAt}}. +Minimal Haxen agent scaffold generated on {{.CreatedAt}}. ## What you get - `main.py` with one router, two reasoners, and one skill - Mock responses so you can run without LLM keys - Commented `app.ai(...)` and `app.call(...)` examples for when you're ready -## Run it with the Brain server -1. **Start the Brain control plane** (from any directory): +## Run it with the Haxen server +1. **Start the Haxen control plane** (from any directory): ```bash - brain dev + haxen dev ``` - This launches the Brain server at `http://localhost:8080`. + This launches the Haxen server at `http://localhost:8080`. 2. **Start this agent** (new terminal, inside the project directory): ```bash - brain run {{.ProjectName}} + haxen run {{.ProjectName}} ``` - The CLI reads `brain-package.yaml`, picks a free port, and registers the node with the Brain server. + The CLI reads `haxen-package.yaml`, picks a free port, and registers the node with the Haxen server. 3. **Optional debugging path:** ```bash @@ -27,10 +27,10 @@ Minimal Brain agent scaffold generated on {{.CreatedAt}}. pip install -e . python main.py ``` - Ensure `BRAIN_SERVER_URL` points at your running Brain server when using this shortcut. + Ensure `HAXEN_SERVER_URL` points at your running Haxen server when using this shortcut. -## Call the reasoner through Brain -All execution flows through the Brain server, not the agent's local port: +## Call the reasoner through Haxen +All execution flows through the Haxen server, not the agent's local port: ```bash curl -X POST \ @@ -44,9 +44,9 @@ The response includes the mock summary plus execution tracking metadata. ## Enable real AI later 1. Add your model keys to `.env` 2. Uncomment the `quickstart.ai(...)` or `quickstart.call(...)` snippets in `main.py` -3. Restart the agent with `brain run {{.ProjectName}}` +3. Restart the agent with `haxen run {{.ProjectName}}` ## Next tweaks -- Rename `node_id` in `main.py` to match your Brain naming scheme +- Rename `node_id` in `main.py` to match your Haxen naming scheme - Add more routers to keep larger projects organized - Replace the mock responses with your actual logic once credentials are in place diff --git a/control-plane/internal/templates/agent/brain-package.yaml.tmpl b/control-plane/internal/templates/agent/haxen-package.yaml.tmpl similarity index 94% rename from control-plane/internal/templates/agent/brain-package.yaml.tmpl rename to control-plane/internal/templates/agent/haxen-package.yaml.tmpl index ce8e930a..7602848d 100644 --- a/control-plane/internal/templates/agent/brain-package.yaml.tmpl +++ b/control-plane/internal/templates/agent/haxen-package.yaml.tmpl @@ -10,7 +10,7 @@ agent_node: default_port: {{.Port}} dependencies: - python: ["brain-sdk"] + python: ["haxen-sdk"] capabilities: reasoners: [] diff --git a/control-plane/internal/templates/agent/brain.yaml.tmpl b/control-plane/internal/templates/agent/haxen.yaml.tmpl similarity index 100% rename from control-plane/internal/templates/agent/brain.yaml.tmpl rename to control-plane/internal/templates/agent/haxen.yaml.tmpl diff --git a/control-plane/internal/templates/agent/main.py.tmpl b/control-plane/internal/templates/agent/main.py.tmpl index 376d717c..23b77ff9 100644 --- a/control-plane/internal/templates/agent/main.py.tmpl +++ b/control-plane/internal/templates/agent/main.py.tmpl @@ -6,14 +6,14 @@ from __future__ import annotations import os from datetime import datetime -from brain_sdk import Agent, AgentRouter +from haxen_sdk import Agent, AgentRouter -# Start the Brain control plane first: `brain dev`. -# Then launch this node via `brain run {{.ProjectName}}` (or use the __main__ block below). -# Feel free to rename this to whatever you call the agent in Brain. +# Start the Haxen control plane first: `haxen dev`. +# Then launch this node via `haxen run {{.ProjectName}}` (or use the __main__ block below). +# Feel free to rename this to whatever you call the agent in Haxen. app = Agent( node_id="{{.NodeID}}", - brain_server=os.getenv("BRAIN_SERVER_URL", "http://localhost:8080"), + haxen_server=os.getenv("HAXEN_SERVER_URL", "http://localhost:8080"), dev_mode=True, ) @@ -71,5 +71,5 @@ app.include_router(quickstart) if __name__ == "__main__": print("🚀 Starting agent — Ctrl+C to stop") - print("ℹ️ Prefer `brain run {{.ProjectName}}` for automatic registration and restarts.") + print("ℹ️ Prefer `haxen run {{.ProjectName}}` for automatic registration and restarts.") app.serve(auto_port=True, host="0.0.0.0") diff --git a/control-plane/internal/templates/agent/pyproject.toml.tmpl b/control-plane/internal/templates/agent/pyproject.toml.tmpl index 1969f68b..acd1c57b 100644 --- a/control-plane/internal/templates/agent/pyproject.toml.tmpl +++ b/control-plane/internal/templates/agent/pyproject.toml.tmpl @@ -5,13 +5,13 @@ build-backend = "setuptools.build_meta" [project] name = "{{.ProjectName}}" version = "0.1.0" -description = "Minimal Brain agent" +description = "Minimal Haxen agent" authors = [{name = "{{.AuthorName}}", email = "{{.AuthorEmail}}"}] readme = "README.md" license = {text = "MIT"} requires-python = ">=3.9" dependencies = [ - "brain-sdk", + "haxen-sdk", "uvicorn>=0.30", ] diff --git a/control-plane/internal/utils/id_generator.go b/control-plane/internal/utils/id_generator.go index 4136153c..84da9dc7 100644 --- a/control-plane/internal/utils/id_generator.go +++ b/control-plane/internal/utils/id_generator.go @@ -27,8 +27,8 @@ func GenerateRunID() string { return fmt.Sprintf("run_%s_%s", timestamp, random) } -// GenerateBrainRequestID generates a new brain request ID -func GenerateBrainRequestID() string { +// GenerateHaxenRequestID generates a new haxen request ID +func GenerateHaxenRequestID() string { timestamp := time.Now().Format("20060102_150405") random := generateRandomString(8) return fmt.Sprintf("req_%s_%s", timestamp, random) diff --git a/control-plane/internal/utils/paths.go b/control-plane/internal/utils/paths.go index 8b41de5c..1d8ce2a9 100644 --- a/control-plane/internal/utils/paths.go +++ b/control-plane/internal/utils/paths.go @@ -6,9 +6,9 @@ import ( "runtime" ) -// DataDirectories holds all the standardized paths for Brain data storage +// DataDirectories holds all the standardized paths for Haxen data storage type DataDirectories struct { - BrainHome string + HaxenHome string DataDir string DatabaseDir string KeysDir string @@ -23,49 +23,49 @@ type DataDirectories struct { PayloadsDir string } -// GetBrainDataDirectories returns the standardized data directories for Brain +// GetHaxenDataDirectories returns the standardized data directories for Haxen // It respects environment variables and provides sensible defaults -func GetBrainDataDirectories() (*DataDirectories, error) { - // Determine Brain home directory - brainHome := os.Getenv("BRAIN_HOME") - if brainHome == "" { +func GetHaxenDataDirectories() (*DataDirectories, error) { + // Determine Haxen home directory + haxenHome := os.Getenv("HAXEN_HOME") + if haxenHome == "" { homeDir, err := os.UserHomeDir() if err != nil { return nil, err } - brainHome = filepath.Join(homeDir, ".brain") + haxenHome = filepath.Join(homeDir, ".haxen") } // Create the data directories structure dirs := &DataDirectories{ - BrainHome: brainHome, - DataDir: filepath.Join(brainHome, "data"), - DatabaseDir: filepath.Join(brainHome, "data"), - KeysDir: filepath.Join(brainHome, "data", "keys"), - DIDRegistriesDir: filepath.Join(brainHome, "data", "did_registries"), - VCsDir: filepath.Join(brainHome, "data", "vcs"), - VCsExecutionsDir: filepath.Join(brainHome, "data", "vcs", "executions"), - VCsWorkflowsDir: filepath.Join(brainHome, "data", "vcs", "workflows"), - AgentsDir: filepath.Join(brainHome, "agents"), - LogsDir: filepath.Join(brainHome, "logs"), - ConfigDir: filepath.Join(brainHome, "config"), - TempDir: filepath.Join(brainHome, "temp"), - PayloadsDir: filepath.Join(brainHome, "data", "payloads"), + HaxenHome: haxenHome, + DataDir: filepath.Join(haxenHome, "data"), + DatabaseDir: filepath.Join(haxenHome, "data"), + KeysDir: filepath.Join(haxenHome, "data", "keys"), + DIDRegistriesDir: filepath.Join(haxenHome, "data", "did_registries"), + VCsDir: filepath.Join(haxenHome, "data", "vcs"), + VCsExecutionsDir: filepath.Join(haxenHome, "data", "vcs", "executions"), + VCsWorkflowsDir: filepath.Join(haxenHome, "data", "vcs", "workflows"), + AgentsDir: filepath.Join(haxenHome, "agents"), + LogsDir: filepath.Join(haxenHome, "logs"), + ConfigDir: filepath.Join(haxenHome, "config"), + TempDir: filepath.Join(haxenHome, "temp"), + PayloadsDir: filepath.Join(haxenHome, "data", "payloads"), } return dirs, nil } -// EnsureDataDirectories creates all necessary Brain data directories +// EnsureDataDirectories creates all necessary Haxen data directories func EnsureDataDirectories() (*DataDirectories, error) { - dirs, err := GetBrainDataDirectories() + dirs, err := GetHaxenDataDirectories() if err != nil { return nil, err } // Create all directories with appropriate permissions directoriesToCreate := []string{ - dirs.BrainHome, + dirs.HaxenHome, dirs.DataDir, dirs.DatabaseDir, dirs.KeysDir, @@ -101,36 +101,36 @@ func EnsureDataDirectories() (*DataDirectories, error) { return dirs, nil } -// GetDatabasePath returns the path to the main Brain database +// GetDatabasePath returns the path to the main Haxen database func GetDatabasePath() (string, error) { - dirs, err := GetBrainDataDirectories() + dirs, err := GetHaxenDataDirectories() if err != nil { return "", err } - return filepath.Join(dirs.DatabaseDir, "brain.db"), nil + return filepath.Join(dirs.DatabaseDir, "haxen.db"), nil } -// GetKVStorePath returns the path to the Brain key-value store +// GetKVStorePath returns the path to the Haxen key-value store func GetKVStorePath() (string, error) { - dirs, err := GetBrainDataDirectories() + dirs, err := GetHaxenDataDirectories() if err != nil { return "", err } - return filepath.Join(dirs.DatabaseDir, "brain.bolt"), nil + return filepath.Join(dirs.DatabaseDir, "haxen.bolt"), nil } // GetAgentRegistryPath returns the path to the agent registry file func GetAgentRegistryPath() (string, error) { - dirs, err := GetBrainDataDirectories() + dirs, err := GetHaxenDataDirectories() if err != nil { return "", err } - return filepath.Join(dirs.BrainHome, "installed.json"), nil + return filepath.Join(dirs.HaxenHome, "installed.json"), nil } // GetConfigPath returns the path to a configuration file func GetConfigPath(filename string) (string, error) { - dirs, err := GetBrainDataDirectories() + dirs, err := GetHaxenDataDirectories() if err != nil { return "", err } @@ -139,7 +139,7 @@ func GetConfigPath(filename string) (string, error) { // GetLogPath returns the path to a log file func GetLogPath(filename string) (string, error) { - dirs, err := GetBrainDataDirectories() + dirs, err := GetHaxenDataDirectories() if err != nil { return "", err } @@ -148,7 +148,7 @@ func GetLogPath(filename string) (string, error) { // GetTempPath returns the path to a temporary file func GetTempPath(filename string) (string, error) { - dirs, err := GetBrainDataDirectories() + dirs, err := GetHaxenDataDirectories() if err != nil { return "", err } @@ -181,13 +181,13 @@ func GetPlatformSpecificPaths() map[string]string { // ValidatePaths checks if all required paths are accessible func ValidatePaths() error { - dirs, err := GetBrainDataDirectories() + dirs, err := GetHaxenDataDirectories() if err != nil { return err } - // Check if we can write to the Brain home directory - testFile := filepath.Join(dirs.BrainHome, ".write_test") + // Check if we can write to the Haxen home directory + testFile := filepath.Join(dirs.HaxenHome, ".write_test") if err := os.WriteFile(testFile, []byte("test"), 0644); err != nil { return err } diff --git a/control-plane/migrations/000_migration_runner.sql b/control-plane/migrations/000_migration_runner.sql index 5e4795ed..87990c42 100644 --- a/control-plane/migrations/000_migration_runner.sql +++ b/control-plane/migrations/000_migration_runner.sql @@ -1,9 +1,9 @@ -- Migration Runner: DID Schema Migration Script --- Description: Complete DID database schema setup for the Brain platform +-- Description: Complete DID database schema setup for the Haxen platform -- Created: 2025-01-08 -- -- This script creates all necessary tables for the DID (Decentralized Identity) implementation --- in the Brain platform, enabling the transition from file-based to database-backed storage. +-- in the Haxen platform, enabling the transition from file-based to database-backed storage. -- Create migrations tracking table CREATE TABLE IF NOT EXISTS schema_migrations ( diff --git a/control-plane/migrations/008_fix_brain_server_id_schema.sql b/control-plane/migrations/008_fix_haxen_server_id_schema.sql similarity index 62% rename from control-plane/migrations/008_fix_brain_server_id_schema.sql rename to control-plane/migrations/008_fix_haxen_server_id_schema.sql index ec137825..c6734a8e 100644 --- a/control-plane/migrations/008_fix_brain_server_id_schema.sql +++ b/control-plane/migrations/008_fix_haxen_server_id_schema.sql @@ -1,21 +1,21 @@ --- Migration: Fix Brain Server ID Schema Inconsistency --- Description: Update schema to use brain_server_id consistently instead of organization_id +-- Migration: Fix Haxen Server ID Schema Inconsistency +-- Description: Update schema to use haxen_server_id consistently instead of organization_id -- Created: 2025-01-21 --- Step 1: Add brain_server_id column to did_registry table -ALTER TABLE did_registry ADD COLUMN brain_server_id TEXT; +-- Step 1: Add haxen_server_id column to did_registry table +ALTER TABLE did_registry ADD COLUMN haxen_server_id TEXT; --- Step 2: Copy organization_id values to brain_server_id for existing records -UPDATE did_registry SET brain_server_id = organization_id WHERE brain_server_id IS NULL; +-- Step 2: Copy organization_id values to haxen_server_id for existing records +UPDATE did_registry SET haxen_server_id = organization_id WHERE haxen_server_id IS NULL; --- Step 3: Make brain_server_id NOT NULL and add unique constraint --- First, ensure all records have brain_server_id populated -UPDATE did_registry SET brain_server_id = 'default' WHERE brain_server_id IS NULL OR brain_server_id = ''; +-- Step 3: Make haxen_server_id NOT NULL and add unique constraint +-- First, ensure all records have haxen_server_id populated +UPDATE did_registry SET haxen_server_id = 'default' WHERE haxen_server_id IS NULL OR haxen_server_id = ''; -- Now make it NOT NULL -- Note: SQLite doesn't support ALTER COLUMN, so we need to recreate the table CREATE TABLE did_registry_new ( - brain_server_id TEXT PRIMARY KEY, + haxen_server_id TEXT PRIMARY KEY, organization_id TEXT, -- Keep for backward compatibility during transition master_seed_encrypted BLOB NOT NULL, root_did TEXT NOT NULL UNIQUE, @@ -26,8 +26,8 @@ CREATE TABLE did_registry_new ( ); -- Copy data from old table to new table -INSERT INTO did_registry_new (brain_server_id, organization_id, master_seed_encrypted, root_did, agent_nodes, total_dids, created_at, last_key_rotation) -SELECT brain_server_id, organization_id, master_seed_encrypted, root_did, agent_nodes, total_dids, created_at, last_key_rotation +INSERT INTO did_registry_new (haxen_server_id, organization_id, master_seed_encrypted, root_did, agent_nodes, total_dids, created_at, last_key_rotation) +SELECT haxen_server_id, organization_id, master_seed_encrypted, root_did, agent_nodes, total_dids, created_at, last_key_rotation FROM did_registry; -- Drop old table and rename new table @@ -40,20 +40,20 @@ CREATE INDEX IF NOT EXISTS idx_did_registry_created_at ON did_registry(created_a CREATE INDEX IF NOT EXISTS idx_did_registry_last_key_rotation ON did_registry(last_key_rotation); CREATE INDEX IF NOT EXISTS idx_did_registry_organization_id ON did_registry(organization_id); -- For backward compatibility --- Step 4: Update agent_dids table to use brain_server_id -ALTER TABLE agent_dids ADD COLUMN brain_server_id TEXT; +-- Step 4: Update agent_dids table to use haxen_server_id +ALTER TABLE agent_dids ADD COLUMN haxen_server_id TEXT; --- Copy organization_id values to brain_server_id for existing records -UPDATE agent_dids SET brain_server_id = organization_id WHERE brain_server_id IS NULL; +-- Copy organization_id values to haxen_server_id for existing records +UPDATE agent_dids SET haxen_server_id = organization_id WHERE haxen_server_id IS NULL; --- Ensure all records have brain_server_id populated -UPDATE agent_dids SET brain_server_id = 'default' WHERE brain_server_id IS NULL OR brain_server_id = ''; +-- Ensure all records have haxen_server_id populated +UPDATE agent_dids SET haxen_server_id = 'default' WHERE haxen_server_id IS NULL OR haxen_server_id = ''; --- Recreate agent_dids table with brain_server_id as the foreign key +-- Recreate agent_dids table with haxen_server_id as the foreign key CREATE TABLE agent_dids_new ( did TEXT PRIMARY KEY, agent_node_id TEXT NOT NULL, - brain_server_id TEXT NOT NULL, + haxen_server_id TEXT NOT NULL, organization_id TEXT, -- Keep for backward compatibility during transition public_key_jwk TEXT NOT NULL, -- JSON Web Key format derivation_path TEXT NOT NULL, @@ -65,12 +65,12 @@ CREATE TABLE agent_dids_new ( updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- Foreign key constraints - FOREIGN KEY (brain_server_id) REFERENCES did_registry(brain_server_id) ON DELETE CASCADE + FOREIGN KEY (haxen_server_id) REFERENCES did_registry(haxen_server_id) ON DELETE CASCADE ); -- Copy data from old table to new table -INSERT INTO agent_dids_new (did, agent_node_id, brain_server_id, organization_id, public_key_jwk, derivation_path, reasoners, skills, status, registered_at, created_at, updated_at) -SELECT did, agent_node_id, brain_server_id, organization_id, public_key_jwk, derivation_path, reasoners, skills, status, registered_at, created_at, updated_at +INSERT INTO agent_dids_new (did, agent_node_id, haxen_server_id, organization_id, public_key_jwk, derivation_path, reasoners, skills, status, registered_at, created_at, updated_at) +SELECT did, agent_node_id, haxen_server_id, organization_id, public_key_jwk, derivation_path, reasoners, skills, status, registered_at, created_at, updated_at FROM agent_dids; -- Drop old table and rename new table @@ -79,8 +79,8 @@ ALTER TABLE agent_dids_new RENAME TO agent_dids; -- Recreate indexes for performance CREATE INDEX IF NOT EXISTS idx_agent_dids_agent_node_id ON agent_dids(agent_node_id); -CREATE INDEX IF NOT EXISTS idx_agent_dids_brain_server_id ON agent_dids(brain_server_id); +CREATE INDEX IF NOT EXISTS idx_agent_dids_haxen_server_id ON agent_dids(haxen_server_id); CREATE INDEX IF NOT EXISTS idx_agent_dids_organization_id ON agent_dids(organization_id); -- For backward compatibility CREATE INDEX IF NOT EXISTS idx_agent_dids_status ON agent_dids(status); CREATE INDEX IF NOT EXISTS idx_agent_dids_registered_at ON agent_dids(registered_at); -CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_dids_agent_node_brain_server ON agent_dids(agent_node_id, brain_server_id); \ No newline at end of file +CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_dids_agent_node_haxen_server ON agent_dids(agent_node_id, haxen_server_id); \ No newline at end of file diff --git a/control-plane/migrations/README.md b/control-plane/migrations/README.md index 4c81f95f..0ceb4dcb 100644 --- a/control-plane/migrations/README.md +++ b/control-plane/migrations/README.md @@ -1,6 +1,6 @@ # DID Database Schema Migrations -This directory contains SQL migration files for the DID (Decentralized Identity) implementation in the Brain platform. These migrations create the necessary database tables to support DID-based authentication, verifiable credentials, and workflow execution tracking. +This directory contains SQL migration files for the DID (Decentralized Identity) implementation in the Haxen platform. These migrations create the necessary database tables to support DID-based authentication, verifiable credentials, and workflow execution tracking. ## Migration Files @@ -106,18 +106,18 @@ Execute the migration files in order, or use the complete migration runner: ```sql -- Option 1: Run complete migration -.read brain/migrations/000_migration_runner.sql +.read haxen/migrations/000_migration_runner.sql -- Option 2: Run individual migrations -.read brain/migrations/001_create_did_registry.sql -.read brain/migrations/002_create_agent_dids.sql -.read brain/migrations/003_create_component_dids.sql -.read brain/migrations/004_create_execution_vcs.sql -.read brain/migrations/005_create_workflow_vcs.sql +.read haxen/migrations/001_create_did_registry.sql +.read haxen/migrations/002_create_agent_dids.sql +.read haxen/migrations/003_create_component_dids.sql +.read haxen/migrations/004_create_execution_vcs.sql +.read haxen/migrations/005_create_workflow_vcs.sql ``` ### Integration with Go Services -The existing DID services in `brain/internal/services/` and types in `brain/pkg/types/did_types.go` are designed to work with these database tables. The migration from file-based storage to database storage should be seamless. +The existing DID services in `haxen/internal/services/` and types in `haxen/pkg/types/did_types.go` are designed to work with these database tables. The migration from file-based storage to database storage should be seamless. ## Migration from File Storage diff --git a/control-plane/pkg/adminpb/reasoner_admin.pb.go b/control-plane/pkg/adminpb/reasoner_admin.pb.go index f7ed42b0..68cb79ee 100644 --- a/control-plane/pkg/adminpb/reasoner_admin.pb.go +++ b/control-plane/pkg/adminpb/reasoner_admin.pb.go @@ -211,7 +211,7 @@ const file_proto_admin_reasoner_admin_proto_rawDesc = "" + "\x15ListReasonersResponse\x120\n" + "\treasoners\x18\x01 \x03(\v2\x12.admin.v1.ReasonerR\treasoners2h\n" + "\x14AdminReasonerService\x12P\n" + - "\rListReasoners\x12\x1e.admin.v1.ListReasonersRequest\x1a\x1f.admin.v1.ListReasonersResponseB\x1bZ\x19brain/pkg/adminpb;adminpbb\x06proto3" + "\rListReasoners\x12\x1e.admin.v1.ListReasonersRequest\x1a\x1f.admin.v1.ListReasonersResponseB\x1bZ\x19haxen/pkg/adminpb;adminpbb\x06proto3" var ( file_proto_admin_reasoner_admin_proto_rawDescOnce sync.Once diff --git a/control-plane/pkg/types/did_types.go b/control-plane/pkg/types/did_types.go index e3b7eb4b..50dfbebf 100644 --- a/control-plane/pkg/types/did_types.go +++ b/control-plane/pkg/types/did_types.go @@ -5,9 +5,9 @@ import ( "time" ) -// DIDRegistry represents the master DID registry for a brain server. +// DIDRegistry represents the master DID registry for a haxen server. type DIDRegistry struct { - BrainServerID string `json:"brain_server_id" db:"brain_server_id"` + HaxenServerID string `json:"haxen_server_id" db:"haxen_server_id"` MasterSeed []byte `json:"master_seed" db:"master_seed_encrypted"` RootDID string `json:"root_did" db:"root_did"` AgentNodes map[string]AgentDIDInfo `json:"agent_nodes" db:"agent_nodes"` @@ -20,7 +20,7 @@ type DIDRegistry struct { type AgentDIDInfo struct { DID string `json:"did" db:"did"` AgentNodeID string `json:"agent_node_id" db:"agent_node_id"` - BrainServerID string `json:"brain_server_id" db:"brain_server_id"` + HaxenServerID string `json:"haxen_server_id" db:"haxen_server_id"` PublicKeyJWK json.RawMessage `json:"public_key_jwk" db:"public_key_jwk"` DerivationPath string `json:"derivation_path" db:"derivation_path"` Reasoners map[string]ReasonerDIDInfo `json:"reasoners" db:"reasoners"` @@ -105,7 +105,7 @@ type DIDIdentityPackage struct { AgentDID DIDIdentity `json:"agent_did"` ReasonerDIDs map[string]DIDIdentity `json:"reasoner_dids"` SkillDIDs map[string]DIDIdentity `json:"skill_dids"` - BrainServerID string `json:"brain_server_id"` + HaxenServerID string `json:"haxen_server_id"` } // DIDIdentity represents a single DID identity with keys. @@ -219,7 +219,7 @@ type VCProof struct { // DIDFilters holds filters for querying DIDs. type DIDFilters struct { - BrainServerID *string `json:"brain_server_id,omitempty"` + HaxenServerID *string `json:"haxen_server_id,omitempty"` AgentNodeID *string `json:"agent_node_id,omitempty"` ComponentType *string `json:"component_type,omitempty"` Status *AgentDIDStatus `json:"status,omitempty"` @@ -354,9 +354,9 @@ type WorkflowVCInfo struct { DocumentSize int64 `json:"document_size_bytes" db:"document_size_bytes"` } -// BrainServerDIDInfo represents brain server-level DID information stored in the database. -type BrainServerDIDInfo struct { - BrainServerID string `json:"brain_server_id" db:"brain_server_id"` +// HaxenServerDIDInfo represents haxen server-level DID information stored in the database. +type HaxenServerDIDInfo struct { + HaxenServerID string `json:"haxen_server_id" db:"haxen_server_id"` RootDID string `json:"root_did" db:"root_did"` MasterSeed []byte `json:"master_seed" db:"master_seed_encrypted"` CreatedAt time.Time `json:"created_at" db:"created_at"` diff --git a/control-plane/pkg/types/status.go b/control-plane/pkg/types/status.go index 0da82ede..b44872f4 100644 --- a/control-plane/pkg/types/status.go +++ b/control-plane/pkg/types/status.go @@ -46,7 +46,7 @@ var executionStatusAliases = map[string]ExecutionStatus{ "processing": ExecutionStatusRunning, } -// NormalizeExecutionStatus maps arbitrary status strings onto the canonical execution statuses used by the Brain platform. +// NormalizeExecutionStatus maps arbitrary status strings onto the canonical execution statuses used by the Haxen platform. // Unknown or unsupported statuses resolve to ExecutionStatusUnknown. func NormalizeExecutionStatus(status string) string { normalized := ExecutionStatus(strings.ToLower(strings.TrimSpace(status))) diff --git a/control-plane/pkg/types/types.go b/control-plane/pkg/types/types.go index 396ee0d2..21f5e3b1 100644 --- a/control-plane/pkg/types/types.go +++ b/control-plane/pkg/types/types.go @@ -157,7 +157,7 @@ type AgentNode struct { Metadata AgentMetadata `json:"metadata" db:"metadata"` } -// CallbackDiscoveryInfo captures how the Brain server resolved an agent callback URL. +// CallbackDiscoveryInfo captures how the Haxen server resolved an agent callback URL. type CallbackDiscoveryInfo struct { Mode string `json:"mode,omitempty"` Preferred string `json:"preferred,omitempty"` @@ -601,7 +601,7 @@ type WorkflowExecution struct { // Core IDs WorkflowID string `json:"workflow_id" db:"workflow_id"` ExecutionID string `json:"execution_id" db:"execution_id"` - BrainRequestID string `json:"brain_request_id" db:"brain_request_id"` + HaxenRequestID string `json:"haxen_request_id" db:"haxen_request_id"` RunID *string `json:"run_id,omitempty" db:"run_id"` SessionID *string `json:"session_id,omitempty" db:"session_id"` ActorID *string `json:"actor_id,omitempty" db:"actor_id"` diff --git a/control-plane/pkg/types/webhook.go b/control-plane/pkg/types/webhook.go index 1e218cfc..3994f9f4 100644 --- a/control-plane/pkg/types/webhook.go +++ b/control-plane/pkg/types/webhook.go @@ -38,7 +38,7 @@ type ExecutionWebhookStateUpdate struct { LastError *string } -// ExecutionWebhookPayload defines the shape Brain sends to webhook consumers. +// ExecutionWebhookPayload defines the shape Haxen sends to webhook consumers. type ExecutionWebhookPayload struct { Event string `json:"event"` ExecutionID string `json:"execution_id"` diff --git a/control-plane/proto/admin/reasoner_admin.proto b/control-plane/proto/admin/reasoner_admin.proto index cce7e975..9a9389b0 100644 --- a/control-plane/proto/admin/reasoner_admin.proto +++ b/control-plane/proto/admin/reasoner_admin.proto @@ -2,7 +2,7 @@ syntax = "proto3"; package admin.v1; -option go_package = "github.com/your-org/brain/control-plane/pkg/adminpb;adminpb"; +option go_package = "github.com/your-org/haxen/control-plane/pkg/adminpb;adminpb"; // AdminReasonerService exposes control-surface operations for reasoning components. service AdminReasonerService { diff --git a/control-plane/scripts/README.md b/control-plane/scripts/README.md index a61f5a7e..43b8ff9e 100644 --- a/control-plane/scripts/README.md +++ b/control-plane/scripts/README.md @@ -1,6 +1,6 @@ -# Brain Server Release Scripts +# Haxen Server Release Scripts -This directory contains automation scripts for building and releasing Brain Server binaries to GitHub. +This directory contains automation scripts for building and releasing Haxen Server binaries to GitHub. ## Overview @@ -95,13 +95,13 @@ User-friendly installation script for end users. **Usage:** ```bash # Quick install (user-specific, no sudo) -curl -sSL https://raw.githubusercontent.com/your-org/brain/main/scripts/install.sh | bash +curl -sSL https://raw.githubusercontent.com/your-org/haxen/main/scripts/install.sh | bash # System-wide install (requires sudo) -curl -sSL https://raw.githubusercontent.com/your-org/brain/main/scripts/install.sh | bash -s -- --system +curl -sSL https://raw.githubusercontent.com/your-org/haxen/main/scripts/install.sh | bash -s -- --system # Custom directory -curl -sSL https://raw.githubusercontent.com/your-org/brain/main/scripts/install.sh | bash -s -- --dir ~/bin +curl -sSL https://raw.githubusercontent.com/your-org/haxen/main/scripts/install.sh | bash -s -- --dir ~/bin ``` ## Workflow @@ -110,7 +110,7 @@ curl -sSL https://raw.githubusercontent.com/your-org/brain/main/scripts/install. 1. **Prepare for release:** ```bash - cd apps/platform/brain/scripts + cd apps/platform/haxen/scripts ./release.sh dry-run # Check prerequisites and preview ``` @@ -142,10 +142,10 @@ curl -sSL https://raw.githubusercontent.com/your-org/brain/main/scripts/install. ### Build Output Each release creates these assets: -- `brain-linux-amd64` - Linux Intel/AMD binary -- `brain-linux-arm64` - Linux ARM binary -- `brain-darwin-amd64` - macOS Intel binary -- `brain-darwin-arm64` - macOS Apple Silicon binary +- `haxen-linux-amd64` - Linux Intel/AMD binary +- `haxen-linux-arm64` - Linux ARM binary +- `haxen-darwin-amd64` - macOS Intel binary +- `haxen-darwin-arm64` - macOS Apple Silicon binary - `checksums.txt` - SHA256 checksums - `build-info.txt` - Build metadata - `README.md` - Installation instructions @@ -153,7 +153,7 @@ Each release creates these assets: ## Configuration ### GitHub Repository -The scripts are configured for: `your-org/brain` +The scripts are configured for: `your-org/haxen` To change the repository, set the environment variable: ```bash @@ -164,7 +164,7 @@ export GITHUB_REPO="your-org/your-repo" ### Build Configuration The release script uses the existing `../build-single-binary.sh` with these settings: - Embedded UI included -- Universal path management (stores data in `~/.brain/`) +- Universal path management (stores data in `~/.haxen/`) - Cross-platform binaries - Single binary deployment @@ -248,7 +248,7 @@ gh release delete v0.1.0-alpha.X ### Complete Release Workflow ```bash # 1. Check current state -cd apps/platform/brain/scripts +cd apps/platform/haxen/scripts ./version-manager.sh info # 2. Test the release process @@ -264,10 +264,10 @@ gh release list ### User Installation Testing ```bash # Test the installation script -curl -sSL https://raw.githubusercontent.com/your-org/brain/main/scripts/install.sh | bash +curl -sSL https://raw.githubusercontent.com/your-org/haxen/main/scripts/install.sh | bash # Verify installation -brain --help +haxen --help ``` ### Build Only (No Release) @@ -282,7 +282,7 @@ ls -la ../dist/releases/ ## File Structure ``` -apps/platform/brain/scripts/ +apps/platform/haxen/scripts/ ├── README.md # This documentation ├── .version # Version tracking file ├── version-manager.sh # Version management script diff --git a/control-plane/scripts/quick-mcp-test.sh b/control-plane/scripts/quick-mcp-test.sh index 47bb3b09..3eff5251 100755 --- a/control-plane/scripts/quick-mcp-test.sh +++ b/control-plane/scripts/quick-mcp-test.sh @@ -4,34 +4,34 @@ # Quick MCP Endpoints Test Script # ============================================================================= # A simplified version for quick testing of MCP endpoints -# Usage: ./brain/scripts/quick-mcp-test.sh +# Usage: ./haxen/scripts/quick-mcp-test.sh # ============================================================================= -BRAIN_SERVER="${BRAIN_SERVER:-http://localhost:8080}" +HAXEN_SERVER="${HAXEN_SERVER:-http://localhost:8080}" echo "🧠 Quick MCP Endpoints Test" echo "==========================" -echo "Server: $BRAIN_SERVER" +echo "Server: $HAXEN_SERVER" echo "" # Check if server is running -echo "1. Checking Brain server..." -if curl -s --connect-timeout 5 "$BRAIN_SERVER/health" > /dev/null; then - echo "✅ Brain server is running" +echo "1. Checking Haxen server..." +if curl -s --connect-timeout 5 "$HAXEN_SERVER/health" > /dev/null; then + echo "✅ Haxen server is running" else - echo "❌ Brain server is not responding" + echo "❌ Haxen server is not responding" exit 1 fi # Test overall MCP status echo "" echo "2. Testing overall MCP status..." -curl -s "$BRAIN_SERVER/api/ui/v1/mcp/status" | jq . 2>/dev/null || echo "❌ Failed to get MCP status" +curl -s "$HAXEN_SERVER/api/ui/v1/mcp/status" | jq . 2>/dev/null || echo "❌ Failed to get MCP status" # Get first node ID echo "" echo "3. Getting available nodes..." -FIRST_NODE=$(curl -s "$BRAIN_SERVER/api/ui/v1/nodes" | jq -r '.[0].id // empty' 2>/dev/null) +FIRST_NODE=$(curl -s "$HAXEN_SERVER/api/ui/v1/nodes" | jq -r '.[0].id // empty' 2>/dev/null) if [ -n "$FIRST_NODE" ] && [ "$FIRST_NODE" != "null" ]; then echo "✅ Found node: $FIRST_NODE" @@ -39,12 +39,12 @@ if [ -n "$FIRST_NODE" ] && [ "$FIRST_NODE" != "null" ]; then # Test node MCP health echo "" echo "4. Testing node MCP health..." - curl -s "$BRAIN_SERVER/api/ui/v1/nodes/$FIRST_NODE/mcp/health" | jq . 2>/dev/null || echo "❌ Failed to get node MCP health" + curl -s "$HAXEN_SERVER/api/ui/v1/nodes/$FIRST_NODE/mcp/health" | jq . 2>/dev/null || echo "❌ Failed to get node MCP health" # Test developer mode echo "" echo "5. Testing developer mode..." - curl -s "$BRAIN_SERVER/api/ui/v1/nodes/$FIRST_NODE/mcp/health?mode=developer" | jq . 2>/dev/null || echo "❌ Failed to get developer mode health" + curl -s "$HAXEN_SERVER/api/ui/v1/nodes/$FIRST_NODE/mcp/health?mode=developer" | jq . 2>/dev/null || echo "❌ Failed to get developer mode health" else echo "⚠️ No nodes found - skipping node-specific tests" fi @@ -53,4 +53,4 @@ echo "" echo "🎉 Quick test completed!" echo "" echo "For comprehensive testing, run:" -echo " ./brain/scripts/test-mcp-endpoints.sh" \ No newline at end of file +echo " ./haxen/scripts/test-mcp-endpoints.sh" \ No newline at end of file diff --git a/control-plane/scripts/release.sh b/control-plane/scripts/release.sh index 1fff2a13..a2721c97 100755 --- a/control-plane/scripts/release.sh +++ b/control-plane/scripts/release.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Brain Release Automation Script +# Haxen Release Automation Script # Builds binaries and creates GitHub releases with auto-incrementing versions set -e @@ -21,9 +21,9 @@ BUILD_SCRIPT="$PROJECT_ROOT/build-single-binary.sh" DIST_DIR="$PROJECT_ROOT/dist/releases" # GitHub configuration -GITHUB_REPO="your-org/brain" +GITHUB_REPO="your-org/haxen" GITHUB_OWNER="your-org" -GITHUB_REPO_NAME="brain" +GITHUB_REPO_NAME="haxen" print_header() { echo -e "${CYAN}================================${NC}" @@ -187,10 +187,10 @@ build_binaries() { # Check for expected binaries local expected_binaries=( - "brain-linux-amd64" - "brain-linux-arm64" - "brain-darwin-amd64" - "brain-darwin-arm64" + "haxen-linux-amd64" + "haxen-linux-arm64" + "haxen-darwin-amd64" + "haxen-darwin-arm64" ) local missing_binaries=() @@ -220,7 +220,7 @@ build_binaries() { # Show build summary print_status "Built files:" - ls -la "$DIST_DIR" | grep -E "(brain-|checksums|build-info|README)" + ls -la "$DIST_DIR" | grep -E "(haxen-|checksums|build-info|README)" } # Generate release notes @@ -236,9 +236,9 @@ generate_release_notes() { fi cat > "$release_notes_file" << EOF -# Brain $NEXT_TAG (Pre-release) +# Haxen $NEXT_TAG (Pre-release) -This is a pre-release version of Brain for testing purposes. +This is a pre-release version of Haxen for testing purposes. ## 🚀 What's New @@ -252,9 +252,9 @@ EOF else echo "### Initial Alpha Release" >> "$release_notes_file" echo "" >> "$release_notes_file" - echo "- Initial release of Brain Server" >> "$release_notes_file" + echo "- Initial release of Haxen Server" >> "$release_notes_file" echo "- Single binary deployment with embedded UI" >> "$release_notes_file" - echo "- Universal path management (stores data in ~/.brain/)" >> "$release_notes_file" + echo "- Universal path management (stores data in ~/.haxen/)" >> "$release_notes_file" echo "- Cross-platform support (Linux, macOS)" >> "$release_notes_file" fi @@ -264,38 +264,38 @@ EOF ### Quick Install (Recommended) ```bash - curl -sSL https://raw.githubusercontent.com/your-org/brain/main/scripts/install.sh | bash + curl -sSL https://raw.githubusercontent.com/your-org/haxen/main/scripts/install.sh | bash ``` ### Manual Download 1. Download the appropriate binary for your platform from the assets below -2. Make it executable: `chmod +x brain-*` -3. Run: `./brain-linux-amd64` (or your platform's binary) +2. Make it executable: `chmod +x haxen-*` +3. Run: `./haxen-linux-amd64` (or your platform's binary) 4. Open http://localhost:8080 in your browser ## 🏗️ Available Binaries -- **brain-linux-amd64** - Linux (Intel/AMD 64-bit) -- **brain-linux-arm64** - Linux (ARM 64-bit) -- **brain-darwin-amd64** - macOS (Intel) -- **brain-darwin-arm64** - macOS (Apple Silicon) +- **haxen-linux-amd64** - Linux (Intel/AMD 64-bit) +- **haxen-linux-arm64** - Linux (ARM 64-bit) +- **haxen-darwin-amd64** - macOS (Intel) +- **haxen-darwin-arm64** - macOS (Apple Silicon) ## 🔧 Features - **Single Binary**: Everything bundled in one executable -- **Universal Storage**: All data stored in `~/.brain/` directory +- **Universal Storage**: All data stored in `~/.haxen/` directory - **Embedded UI**: Web interface included in binary - **Cross-Platform**: Works on Linux and macOS - **Portable**: Run from anywhere, data stays consistent ## 📁 Data Directory -All Brain data is stored in `~/.brain/`: +All Haxen data is stored in `~/.haxen/`: ``` -~/.brain/ +~/.haxen/ ├── data/ -│ ├── brain.db # Main database -│ ├── brain.bolt # Cache +│ ├── haxen.db # Main database +│ ├── haxen.bolt # Cache │ ├── keys/ # Cryptographic keys │ ├── did_registries/ # DID registries │ └── vcs/ # Verifiable credentials @@ -310,7 +310,7 @@ This is an alpha pre-release intended for testing and development. Not recommend ## 🐛 Issues & Support -Report issues at: https://github.com/your-org/brain/issues +Report issues at: https://github.com/your-org/haxen/issues EOF @@ -338,7 +338,7 @@ create_github_release() { # Create GitHub release print_status "Creating GitHub release..." gh release create "$NEXT_TAG" \ - --title "Brain $NEXT_TAG" \ + --title "Haxen $NEXT_TAG" \ --notes-file "$release_notes_file" \ --prerelease \ --repo "$GITHUB_REPO" @@ -354,10 +354,10 @@ upload_assets() { # List of assets to upload local assets=( - "brain-linux-amd64" - "brain-linux-arm64" - "brain-darwin-amd64" - "brain-darwin-arm64" + "haxen-linux-amd64" + "haxen-linux-arm64" + "haxen-darwin-amd64" + "haxen-darwin-arm64" "checksums.txt" "build-info.txt" "README.md" @@ -413,7 +413,7 @@ cleanup() { # Main release function main() { - print_header "Brain Server Release Automation" + print_header "Haxen Server Release Automation" echo "This script will:" echo " • Check prerequisites and authentication" @@ -459,7 +459,7 @@ case "${1:-}" in print_success "Build completed - no release created" ;; "help"|"-h"|"--help") - echo "Brain Release Automation Script" + echo "Haxen Release Automation Script" echo "" echo "Usage:" echo " $0 Create full release (build + GitHub release)" diff --git a/control-plane/scripts/test-mcp-endpoints.sh b/control-plane/scripts/test-mcp-endpoints.sh index bc6ad1b4..3d088af4 100755 --- a/control-plane/scripts/test-mcp-endpoints.sh +++ b/control-plane/scripts/test-mcp-endpoints.sh @@ -4,25 +4,25 @@ # MCP Endpoints Testing Script # ============================================================================= # This script tests all the new MCP health integration endpoints implemented -# in the Brain server. It includes comprehensive testing for all 4 endpoints +# in the Haxen server. It includes comprehensive testing for all 4 endpoints # with both success and error scenarios. # # Prerequisites: -# - Brain server running on http://localhost:8080 (default) +# - Haxen server running on http://localhost:8080 (default) # - jq installed for JSON formatting (brew install jq on macOS) # - curl available (should be pre-installed) # - At least one agent node running and registered # # Usage: -# chmod +x brain/scripts/test-mcp-endpoints.sh -# ./brain/scripts/test-mcp-endpoints.sh +# chmod +x haxen/scripts/test-mcp-endpoints.sh +# ./haxen/scripts/test-mcp-endpoints.sh # # ============================================================================= set -e # Exit on any error # Configuration -BRAIN_SERVER="${BRAIN_SERVER:-http://localhost:8080}" +HAXEN_SERVER="${HAXEN_SERVER:-http://localhost:8080}" VERBOSE="${VERBOSE:-false}" SLEEP_BETWEEN_TESTS="${SLEEP_BETWEEN_TESTS:-2}" @@ -74,16 +74,16 @@ check_dependencies() { log_success "All dependencies are available" } -# Check if Brain server is running -check_brain_server() { - log_info "Checking if Brain server is running at $BRAIN_SERVER..." +# Check if Haxen server is running +check_haxen_server() { + log_info "Checking if Haxen server is running at $HAXEN_SERVER..." - if curl -s --connect-timeout 5 "$BRAIN_SERVER/health" > /dev/null 2>&1; then - log_success "Brain server is running" + if curl -s --connect-timeout 5 "$HAXEN_SERVER/health" > /dev/null 2>&1; then + log_success "Haxen server is running" else - log_error "Brain server is not responding at $BRAIN_SERVER" - log_error "Please ensure the Brain server is running:" - log_error " cd brain/apps/platform/brain && go run cmd/brain-server/main.go" + log_error "Haxen server is not responding at $HAXEN_SERVER" + log_error "Please ensure the Haxen server is running:" + log_error " cd haxen/apps/platform/haxen && go run cmd/haxen-server/main.go" exit 1 fi } @@ -93,10 +93,10 @@ get_test_nodes() { log_info "Fetching available nodes for testing..." local response - response=$(curl -s "$BRAIN_SERVER/api/ui/v1/nodes" 2>/dev/null) + response=$(curl -s "$HAXEN_SERVER/api/ui/v1/nodes" 2>/dev/null) if [ $? -ne 0 ] || [ -z "$response" ]; then - log_error "Failed to fetch nodes from Brain server" + log_error "Failed to fetch nodes from Haxen server" return 1 fi @@ -185,7 +185,7 @@ test_overall_mcp_status() { log_separator execute_curl "GET" \ - "$BRAIN_SERVER/api/ui/v1/mcp/status" \ + "$HAXEN_SERVER/api/ui/v1/mcp/status" \ "Get overall MCP status across all nodes" \ "" \ "200" @@ -203,7 +203,7 @@ test_node_mcp_health_user() { fi execute_curl "GET" \ - "$BRAIN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/health" \ + "$HAXEN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/health" \ "Get MCP health for node $FIRST_NODE_ID (user mode)" \ "" \ "200" @@ -221,7 +221,7 @@ test_node_mcp_health_developer() { fi execute_curl "GET" \ - "$BRAIN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/health?mode=developer" \ + "$HAXEN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/health?mode=developer" \ "Get MCP health for node $FIRST_NODE_ID (developer mode)" \ "" \ "200" @@ -241,7 +241,7 @@ test_mcp_server_restart() { # First, try to get available MCP servers for this node log_info "Getting available MCP servers for node $FIRST_NODE_ID..." local health_response - health_response=$(curl -s "$BRAIN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/health?mode=developer" 2>/dev/null) + health_response=$(curl -s "$HAXEN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/health?mode=developer" 2>/dev/null) if [ $? -eq 0 ] && [ -n "$health_response" ]; then local server_alias @@ -250,14 +250,14 @@ test_mcp_server_restart() { if [ -n "$server_alias" ] && [ "$server_alias" != "null" ]; then log_info "Found MCP server alias: $server_alias" execute_curl "POST" \ - "$BRAIN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/servers/$server_alias/restart" \ + "$HAXEN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/servers/$server_alias/restart" \ "Restart MCP server '$server_alias' on node $FIRST_NODE_ID" \ "" \ "200" else log_warning "No MCP servers found for node $FIRST_NODE_ID, testing with dummy alias" execute_curl "POST" \ - "$BRAIN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/servers/test-server/restart" \ + "$HAXEN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/servers/test-server/restart" \ "Restart MCP server 'test-server' on node $FIRST_NODE_ID (should fail)" \ "" \ "404" @@ -265,7 +265,7 @@ test_mcp_server_restart() { else log_warning "Could not fetch MCP servers, testing with dummy alias" execute_curl "POST" \ - "$BRAIN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/servers/test-server/restart" \ + "$HAXEN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/servers/test-server/restart" \ "Restart MCP server 'test-server' on node $FIRST_NODE_ID (should fail)" \ "" \ "404" @@ -286,7 +286,7 @@ test_mcp_tools_listing() { # First, try to get available MCP servers for this node log_info "Getting available MCP servers for node $FIRST_NODE_ID..." local health_response - health_response=$(curl -s "$BRAIN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/health?mode=developer" 2>/dev/null) + health_response=$(curl -s "$HAXEN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/health?mode=developer" 2>/dev/null) if [ $? -eq 0 ] && [ -n "$health_response" ]; then local server_alias @@ -295,14 +295,14 @@ test_mcp_tools_listing() { if [ -n "$server_alias" ] && [ "$server_alias" != "null" ]; then log_info "Found MCP server alias: $server_alias" execute_curl "GET" \ - "$BRAIN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/servers/$server_alias/tools" \ + "$HAXEN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/servers/$server_alias/tools" \ "Get tools for MCP server '$server_alias' on node $FIRST_NODE_ID" \ "" \ "200" else log_warning "No MCP servers found for node $FIRST_NODE_ID, testing with dummy alias" execute_curl "GET" \ - "$BRAIN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/servers/test-server/tools" \ + "$HAXEN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/servers/test-server/tools" \ "Get tools for MCP server 'test-server' on node $FIRST_NODE_ID (should fail)" \ "" \ "404" @@ -310,7 +310,7 @@ test_mcp_tools_listing() { else log_warning "Could not fetch MCP servers, testing with dummy alias" execute_curl "GET" \ - "$BRAIN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/servers/test-server/tools" \ + "$HAXEN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/servers/test-server/tools" \ "Get tools for MCP server 'test-server' on node $FIRST_NODE_ID (should fail)" \ "" \ "404" @@ -325,7 +325,7 @@ test_error_cases() { # Test with invalid node ID execute_curl "GET" \ - "$BRAIN_SERVER/api/ui/v1/nodes/invalid-node-id/mcp/health" \ + "$HAXEN_SERVER/api/ui/v1/nodes/invalid-node-id/mcp/health" \ "Get MCP health for invalid node ID (should fail)" \ "" \ "404" @@ -333,13 +333,13 @@ test_error_cases() { # Test with non-existent server alias if [ -n "$FIRST_NODE_ID" ]; then execute_curl "GET" \ - "$BRAIN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/servers/non-existent-server/tools" \ + "$HAXEN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/servers/non-existent-server/tools" \ "Get tools for non-existent MCP server (should fail)" \ "" \ "404" execute_curl "POST" \ - "$BRAIN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/servers/non-existent-server/restart" \ + "$HAXEN_SERVER/api/ui/v1/nodes/$FIRST_NODE_ID/mcp/servers/non-existent-server/restart" \ "Restart non-existent MCP server (should fail)" \ "" \ "404" @@ -357,7 +357,7 @@ test_sse_events() { # Test SSE connection briefly timeout 5 curl -s -H "Accept: text/event-stream" \ - "$BRAIN_SERVER/api/ui/v1/events" 2>/dev/null || true + "$HAXEN_SERVER/api/ui/v1/events" 2>/dev/null || true log_info "SSE connection test completed (use browser or SSE client for full testing)" } @@ -371,13 +371,13 @@ main() { echo -e "${NC}" log_info "Starting MCP endpoints testing..." - log_info "Brain Server: $BRAIN_SERVER" + log_info "Haxen Server: $HAXEN_SERVER" log_info "Verbose Mode: $VERBOSE" echo "" # Pre-flight checks check_dependencies - check_brain_server + check_haxen_server get_test_nodes # Run all tests @@ -404,10 +404,10 @@ main() { log_info " - Server restart: Success confirmation message" log_info "" log_info "Common troubleshooting:" - log_info " - Ensure Brain server is running: go run cmd/brain-server/main.go" + log_info " - Ensure Haxen server is running: go run cmd/haxen-server/main.go" log_info " - Ensure at least one agent is running and registered" log_info " - Check agent MCP server configurations" - log_info " - Verify network connectivity to $BRAIN_SERVER" + log_info " - Verify network connectivity to $HAXEN_SERVER" echo "" } @@ -420,7 +420,7 @@ while [[ $# -gt 0 ]]; do shift ;; -s|--server) - BRAIN_SERVER="$2" + HAXEN_SERVER="$2" shift 2 ;; -h|--help) @@ -428,11 +428,11 @@ while [[ $# -gt 0 ]]; do echo "" echo "Options:" echo " -v, --verbose Enable verbose curl output" - echo " -s, --server URL Set Brain server URL (default: http://localhost:8080)" + echo " -s, --server URL Set Haxen server URL (default: http://localhost:8080)" echo " -h, --help Show this help message" echo "" echo "Environment variables:" - echo " BRAIN_SERVER Brain server URL" + echo " HAXEN_SERVER Haxen server URL" echo " VERBOSE Enable verbose mode (true/false)" echo " SLEEP_BETWEEN_TESTS Seconds to sleep between tests (default: 2)" exit 0 diff --git a/control-plane/scripts/version-manager.sh b/control-plane/scripts/version-manager.sh index 4801e6b0..d975198b 100755 --- a/control-plane/scripts/version-manager.sh +++ b/control-plane/scripts/version-manager.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Brain Version Manager +# Haxen Version Manager # Handles version tracking and incrementing for releases set -e @@ -237,7 +237,7 @@ main() { show_version_info ;; "help"|"-h"|"--help") - echo "Brain Version Manager" + echo "Haxen Version Manager" echo "" echo "Usage:" echo " $0 current Show current version" diff --git a/control-plane/tools/perf/README.md b/control-plane/tools/perf/README.md index 369426b4..aaea4680 100644 --- a/control-plane/tools/perf/README.md +++ b/control-plane/tools/perf/README.md @@ -5,20 +5,20 @@ path introduced in the orchestration refactor. ## Quick start -1. Build the gateway binary (or run `go run ./cmd/brain-server`). The production +1. Build the gateway binary (or run `go run ./cmd/haxen-server`). The production build script is still the source of truth: ```bash - cd brain/apps/platform/brain + cd haxen/apps/platform/haxen ./build-single-binary.sh - ./dist/releases/brain-darwin-arm64 --config ./configs/local.yaml + ./dist/releases/haxen-darwin-arm64 --config ./configs/local.yaml ``` 2. Install the load-test dependencies in a virtual environment (or build the optional Docker image described below): ```bash - cd brain/apps/platform/brain/tools/perf + cd haxen/apps/platform/haxen/tools/perf python -m venv .venv source .venv/bin/activate pip install -r requirements.txt @@ -48,7 +48,7 @@ path introduced in the orchestration refactor. Build the utility image from the repo root: ```bash -docker build -t brain-perf ./apps/platform/brain/tools/perf +docker build -t haxen-perf ./apps/platform/haxen/tools/perf ``` Run it by either supplying CLI arguments or setting environment variables. @@ -56,7 +56,7 @@ Examples (Linux users may need `--add-host host.docker.internal:host-gateway`): ```bash # Pass arguments directly -docker run --rm --network host brain-perf \ +docker run --rm --network host haxen-perf \ --base-url http://host.docker.internal:8080 \ --target demo-agent.synthetic_nested \ --mode async \ @@ -74,7 +74,7 @@ docker run --rm --network host \ -e PRINT_FAILURES=true \ -e METRICS_URL=http://host.docker.internal:8080/metrics \ -e METRICS=process_resident_memory_bytes,go_goroutines \ - brain-perf + haxen-perf ``` Supported environment variables when no CLI arguments are provided: @@ -101,24 +101,24 @@ so you can mix and match as needed. ### Local gateway stack (SQLite/GORM) -To exercise the harness against a containerised Brain server backed by the new +To exercise the harness against a containerised Haxen server backed by the new SQLite + GORM storage layer, reuse the Docker image from -`apps/platform/brain/docker`: +`apps/platform/haxen/docker`: ```bash -# 1) Build and run the Brain server (see docker/README.md for details) -docker build -t brain-local apps/platform/brain/docker -docker run --rm -d --name brain-local \ +# 1) Build and run the Haxen server (see docker/README.md for details) +docker build -t haxen-local apps/platform/haxen/docker +docker run --rm -d --name haxen-local \ -p 8080:8080 \ - -v "$(pwd)/apps/platform/brain/data:/app/data" \ - brain-local + -v "$(pwd)/apps/platform/haxen/data:/app/data" \ + haxen-local # 2) Drive load with the harness (inside this directory) python nested_workflow_stress.py --base-url http://localhost:8080 \ --target demo-agent.synthetic_nested --requests 200 --concurrency 16 -# 3) Stop the Brain container when finished -docker stop brain-local +# 3) Stop the Haxen container when finished +docker stop haxen-local ``` Because the server persists all durable state in SQLite, no external services or @@ -163,7 +163,7 @@ Example `scenarios.json`: - **Backpressure verification**: Drive queue overload by setting `--requests` well above steady-state capacity. Watch for HTTP 429 responses (`status_counts` will include `queue_full`) and confirm Prometheus metrics - (`brain_gateway_queue_depth`, `brain_gateway_backpressure_total`) move as + (`haxen_gateway_queue_depth`, `haxen_gateway_backpressure_total`) move as expected. - **Memory/CPU sampling**: While the stress harness is running, capture runtime stats (`go tool pprof`, `top`, `ps`, or `gops stats`). Persist the JSON metrics diff --git a/control-plane/tools/perf/nested_workflow_stress.py b/control-plane/tools/perf/nested_workflow_stress.py index f52ab27c..d22d5d4a 100644 --- a/control-plane/tools/perf/nested_workflow_stress.py +++ b/control-plane/tools/perf/nested_workflow_stress.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Lightweight load generator for Brain durable execution flows. +"""Lightweight load generator for Haxen durable execution flows. This script exercises the /execute and /execute/async gateways with configurable concurrency, nested payload parameters, and adaptive polling. It records latency @@ -57,8 +57,8 @@ "process_resident_memory_bytes", "go_memstats_heap_alloc_bytes", "go_goroutines", - "brain_gateway_queue_depth", - "brain_worker_inflight", + "haxen_gateway_queue_depth", + "haxen_worker_inflight", ] import httpx @@ -89,8 +89,8 @@ def load_template(path: Optional[Path]) -> Optional[str]: def build_parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser(description="Brain durable execution load tester") - parser.add_argument("--base-url", default=os.getenv("BRAIN_BASE_URL", "http://localhost:8080")) + parser = argparse.ArgumentParser(description="Haxen durable execution load tester") + parser.add_argument("--base-url", default=os.getenv("HAXEN_BASE_URL", "http://localhost:8080")) parser.add_argument("--target", required=True, help="Target in node.reasoner form") parser.add_argument("--mode", choices=["sync", "async"], default="sync") parser.add_argument("--requests", type=int, default=100) diff --git a/control-plane/web/client/.env b/control-plane/web/client/.env index 23fa57bf..02d5f110 100644 --- a/control-plane/web/client/.env +++ b/control-plane/web/client/.env @@ -1,4 +1,4 @@ -# Development environment variables for Brain UI +# Development environment variables for Haxen UI # These are defaults that can be overridden by .env.local or system environment variables # API Configuration @@ -15,5 +15,5 @@ VITE_BUILD_OUT_DIR=dist VITE_BUILD_SOURCEMAP=false # Application Configuration -VITE_APP_TITLE=Brain Server Dashboard -VITE_APP_DESCRIPTION=Brain AI Agent Orchestration Platform +VITE_APP_TITLE=Haxen Server Dashboard +VITE_APP_DESCRIPTION=Haxen AI Agent Orchestration Platform diff --git a/control-plane/web/client/.env.example b/control-plane/web/client/.env.example index b4489868..7b85a095 100644 --- a/control-plane/web/client/.env.example +++ b/control-plane/web/client/.env.example @@ -1,4 +1,4 @@ -# Brain UI Environment Variables +# Haxen UI Environment Variables # Copy this file to .env.local and modify values as needed # API Configuration @@ -15,8 +15,8 @@ VITE_BUILD_OUT_DIR=dist VITE_BUILD_SOURCEMAP=false # Application Configuration -VITE_APP_TITLE=Brain Server Dashboard -VITE_APP_DESCRIPTION=Brain AI Agent Orchestration Platform +VITE_APP_TITLE=Haxen Server Dashboard +VITE_APP_DESCRIPTION=Haxen AI Agent Orchestration Platform VITE_APP_VERSION=1.0.0 # Feature Flags (optional) diff --git a/control-plane/web/client/.env.production b/control-plane/web/client/.env.production index 679d53ae..9349073e 100644 --- a/control-plane/web/client/.env.production +++ b/control-plane/web/client/.env.production @@ -1,4 +1,4 @@ -# Production environment variables for Brain UI +# Production environment variables for Haxen UI # API Configuration VITE_API_BASE_URL=/api/ui/v1 @@ -9,5 +9,5 @@ VITE_BUILD_OUT_DIR=dist VITE_BUILD_SOURCEMAP=false # Application Configuration -VITE_APP_TITLE=Brain Server Dashboard -VITE_APP_DESCRIPTION=Brain AI Agent Orchestration Platform +VITE_APP_TITLE=Haxen Server Dashboard +VITE_APP_DESCRIPTION=Haxen AI Agent Orchestration Platform diff --git a/control-plane/web/client/index.html b/control-plane/web/client/index.html index 0114dc56..9acc2ce7 100644 --- a/control-plane/web/client/index.html +++ b/control-plane/web/client/index.html @@ -4,7 +4,7 @@ - Brain - Open infrastructure for autonomous software + Haxen - Open infrastructure for autonomous software
diff --git a/control-plane/web/client/src/components/AgentNodesTable.tsx b/control-plane/web/client/src/components/AgentNodesTable.tsx index 83157647..5c204262 100644 --- a/control-plane/web/client/src/components/AgentNodesTable.tsx +++ b/control-plane/web/client/src/components/AgentNodesTable.tsx @@ -1,5 +1,5 @@ import React, { useState } from 'react'; -import type { AgentNodeSummary, AgentNode } from '../types/brain'; +import type { AgentNodeSummary, AgentNode } from '../types/haxen'; import { Table, TableBody, @@ -69,7 +69,7 @@ const AgentNodesTable: React.FC = ({ nodes, isLoading, err

No Agent Nodes

-

No agent nodes are currently registered with the Brain server.

+

No agent nodes are currently registered with the Haxen server.

); } diff --git a/control-plane/web/client/src/components/HealthBadge.tsx b/control-plane/web/client/src/components/HealthBadge.tsx index f441c071..d9978954 100644 --- a/control-plane/web/client/src/components/HealthBadge.tsx +++ b/control-plane/web/client/src/components/HealthBadge.tsx @@ -1,5 +1,5 @@ import React from 'react'; -import type { HealthStatus } from '../types/brain'; +import type { HealthStatus } from '../types/haxen'; import { cn } from '@/lib/utils'; interface HealthBadgeProps { diff --git a/control-plane/web/client/src/components/Navigation/Sidebar.tsx b/control-plane/web/client/src/components/Navigation/Sidebar.tsx index fb77477f..6c703933 100644 --- a/control-plane/web/client/src/components/Navigation/Sidebar.tsx +++ b/control-plane/web/client/src/components/Navigation/Sidebar.tsx @@ -54,7 +54,7 @@ export function Sidebar({ sections, isCollapsed = false }: SidebarProps) { typography["heading-sm"], "text-foreground font-semibold" )}> - Brain + Haxen

- Brain + Haxen Open Control Plane
diff --git a/control-plane/web/client/src/components/NodeCard.tsx b/control-plane/web/client/src/components/NodeCard.tsx index ff9a9e36..114c4097 100644 --- a/control-plane/web/client/src/components/NodeCard.tsx +++ b/control-plane/web/client/src/components/NodeCard.tsx @@ -14,7 +14,7 @@ import { startAgent, stopAgent, reconcileAgent } from "../services/configuration import { AgentControlButton, type AgentState } from "@/components/ui/AgentControlButton"; import { useDIDStatus } from "../hooks/useDIDInfo"; import { cn } from "../lib/utils"; -import type { AgentNodeSummary } from "../types/brain"; +import type { AgentNodeSummary } from "../types/haxen"; import type { DensityMode } from "./DensityToggle"; import { CompositeDIDStatus } from "./did/DIDStatusBadge"; import { DIDIdentityBadge } from "./did/DIDDisplay"; diff --git a/control-plane/web/client/src/components/NodesList.tsx b/control-plane/web/client/src/components/NodesList.tsx index f51ad604..1bd16cff 100644 --- a/control-plane/web/client/src/components/NodesList.tsx +++ b/control-plane/web/client/src/components/NodesList.tsx @@ -1,5 +1,5 @@ import React, { useState, useEffect, useCallback } from 'react'; -import type { AgentNodeSummary } from '../types/brain'; +import type { AgentNodeSummary } from '../types/haxen'; import { getNodesSummary, streamNodeEvents } from '../services/api'; import AgentNodesTable from './AgentNodesTable'; import { Badge } from '@/components/ui/badge'; @@ -28,7 +28,7 @@ const NodesList: React.FC = () => { setTotalCount(data.count); } catch (err) { console.error('Failed to load nodes summary:', err); - setError('Failed to load agent nodes. Please ensure the Brain server is running and accessible.'); + setError('Failed to load agent nodes. Please ensure the Haxen server is running and accessible.'); } finally { setIsLoading(false); } diff --git a/control-plane/web/client/src/components/NodesStatusSummary.tsx b/control-plane/web/client/src/components/NodesStatusSummary.tsx index 54328986..d640f0ac 100644 --- a/control-plane/web/client/src/components/NodesStatusSummary.tsx +++ b/control-plane/web/client/src/components/NodesStatusSummary.tsx @@ -3,7 +3,7 @@ import { summarizeNodeStatuses, getNodeStatusPresentation } from "@/utils/node-s import { Checklist } from "@/components/ui/icon-bridge"; import { cn } from "@/lib/utils"; import { Card } from "@/components/ui/card"; -import type { AgentNodeSummary } from "../types/brain"; +import type { AgentNodeSummary } from "../types/haxen"; interface NodesStatusSummaryProps { nodes: AgentNodeSummary[]; diff --git a/control-plane/web/client/src/components/NodesVirtualList.tsx b/control-plane/web/client/src/components/NodesVirtualList.tsx index 5b2056d6..10412899 100644 --- a/control-plane/web/client/src/components/NodesVirtualList.tsx +++ b/control-plane/web/client/src/components/NodesVirtualList.tsx @@ -10,7 +10,7 @@ import { EmptyMedia, EmptyTitle, } from "@/components/ui/empty"; -import type { AgentNodeSummary } from '../types/brain'; +import type { AgentNodeSummary } from '../types/haxen'; import { NodeCard } from './NodeCard'; import type { DensityMode } from './DensityToggle'; import { getStatusPriority } from './ui/status-indicator'; diff --git a/control-plane/web/client/src/components/ReasonersList.tsx b/control-plane/web/client/src/components/ReasonersList.tsx index 7fd12f58..63833357 100644 --- a/control-plane/web/client/src/components/ReasonersList.tsx +++ b/control-plane/web/client/src/components/ReasonersList.tsx @@ -1,5 +1,5 @@ import React from 'react'; -import type { ReasonerDefinition } from '../types/brain'; +import type { ReasonerDefinition } from '../types/haxen'; import { Badge } from '@/components/ui/badge'; import { WatsonxAi } from '@/components/ui/icon-bridge'; diff --git a/control-plane/web/client/src/components/ReasonersSkillsTable.tsx b/control-plane/web/client/src/components/ReasonersSkillsTable.tsx index 9118428c..d53f199b 100644 --- a/control-plane/web/client/src/components/ReasonersSkillsTable.tsx +++ b/control-plane/web/client/src/components/ReasonersSkillsTable.tsx @@ -19,7 +19,7 @@ import { Identification, } from "@/components/ui/icon-bridge"; import { cn } from "@/lib/utils"; -import type { ReasonerDefinition, SkillDefinition } from "@/types/brain"; +import type { ReasonerDefinition, SkillDefinition } from "@/types/haxen"; import type { ReasonerDIDInfo, SkillDIDInfo } from "@/types/did"; interface ReasonersSkillsTableProps { diff --git a/control-plane/web/client/src/components/SkillsList.tsx b/control-plane/web/client/src/components/SkillsList.tsx index f70efce9..fd77a972 100644 --- a/control-plane/web/client/src/components/SkillsList.tsx +++ b/control-plane/web/client/src/components/SkillsList.tsx @@ -3,7 +3,7 @@ import { Button } from "@/components/ui/button"; import { Card, CardContent } from "@/components/ui/card"; import { Function, Information } from "@/components/ui/icon-bridge"; import React, { useState } from "react"; -import type { SkillDefinition } from "../types/brain"; +import type { SkillDefinition } from "../types/haxen"; import type { AgentDIDInfo, SkillDIDInfo } from "../types/did"; import { DIDIdentityBadge, DIDStatusBadge } from "./did/DIDStatusBadge"; import { useDIDNotifications } from "./ui/notification"; diff --git a/control-plane/web/client/src/components/did/DIDIdentityCard.tsx b/control-plane/web/client/src/components/did/DIDIdentityCard.tsx index 495e5342..6a87c5b0 100644 --- a/control-plane/web/client/src/components/did/DIDIdentityCard.tsx +++ b/control-plane/web/client/src/components/did/DIDIdentityCard.tsx @@ -223,7 +223,7 @@ export function DIDIdentityCard({ - Brain Server: {didInfo.brain_server_id} + Haxen Server: {didInfo.haxen_server_id} diff --git a/control-plane/web/client/src/components/did/DIDInfoModal.tsx b/control-plane/web/client/src/components/did/DIDInfoModal.tsx index 8e802585..4f159be8 100644 --- a/control-plane/web/client/src/components/did/DIDInfoModal.tsx +++ b/control-plane/web/client/src/components/did/DIDInfoModal.tsx @@ -228,10 +228,10 @@ export function DIDInfoModal({ nodeId, isOpen, onClose }: DIDInfoModalProps) {
- Brain Server: + Haxen Server: - {didInfo.brain_server_id} + {didInfo.haxen_server_id}
@@ -398,10 +398,10 @@ export function DIDInfoModal({ nodeId, isOpen, onClose }: DIDInfoModalProps) {
- Brain Server: + Haxen Server:
- {didInfo.brain_server_id} + {didInfo.haxen_server_id}
diff --git a/control-plane/web/client/src/components/execution/EnhancedExecutionHeader.tsx b/control-plane/web/client/src/components/execution/EnhancedExecutionHeader.tsx index 88c5ce51..57209435 100644 --- a/control-plane/web/client/src/components/execution/EnhancedExecutionHeader.tsx +++ b/control-plane/web/client/src/components/execution/EnhancedExecutionHeader.tsx @@ -375,11 +375,11 @@ export function EnhancedExecutionHeader({
Request: - {execution.brain_request_id ? truncateId(execution.brain_request_id) : 'n/a'} + {execution.haxen_request_id ? truncateId(execution.haxen_request_id) : 'n/a'} - {execution.brain_request_id && ( + {execution.haxen_request_id && ( Request: - {execution.brain_request_id - ? truncateId(execution.brain_request_id) + {execution.haxen_request_id + ? truncateId(execution.haxen_request_id) : "n/a"} - {execution.brain_request_id && ( + {execution.haxen_request_id && ( , title: "Getting started", - body: "Launch an agent node to register reasoners with Brain. They will appear here as soon as they are online.", + body: "Launch an agent node to register reasoners with Haxen. They will appear here as soon as they are online.", }, }; diff --git a/control-plane/web/client/src/components/status/StatusBadge.tsx b/control-plane/web/client/src/components/status/StatusBadge.tsx index bebeb0da..c65106a8 100644 --- a/control-plane/web/client/src/components/status/StatusBadge.tsx +++ b/control-plane/web/client/src/components/status/StatusBadge.tsx @@ -4,7 +4,7 @@ import type { AgentStatus, HealthStatus, LifecycleStatus, -} from "@/types/brain"; +} from "@/types/haxen"; import { cn } from "@/lib/utils"; import { statusTone, type StatusTone } from "@/lib/theme"; import { diff --git a/control-plane/web/client/src/components/status/StatusRefreshButton.tsx b/control-plane/web/client/src/components/status/StatusRefreshButton.tsx index 71c8db4d..8a1caf8a 100644 --- a/control-plane/web/client/src/components/status/StatusRefreshButton.tsx +++ b/control-plane/web/client/src/components/status/StatusRefreshButton.tsx @@ -1,6 +1,6 @@ import { Button } from "@/components/ui/button"; import { bulkNodeStatus, refreshNodeStatus } from "@/services/api"; -import type { AgentStatus } from "@/types/brain"; +import type { AgentStatus } from "@/types/haxen"; import { ArrowClockwise } from "@/components/ui/icon-bridge"; import { useState } from "react"; import { cn } from "@/lib/utils"; diff --git a/control-plane/web/client/src/components/status/UnifiedStatusIndicator.tsx b/control-plane/web/client/src/components/status/UnifiedStatusIndicator.tsx index cb0fc2ea..435ba18a 100644 --- a/control-plane/web/client/src/components/status/UnifiedStatusIndicator.tsx +++ b/control-plane/web/client/src/components/status/UnifiedStatusIndicator.tsx @@ -1,5 +1,5 @@ import { Badge } from "@/components/ui/badge"; -import type { AgentState, AgentStatus } from "@/types/brain"; +import type { AgentState, AgentStatus } from "@/types/haxen"; import { cn } from "@/lib/utils"; import { statusTone, type StatusTone } from "@/lib/theme"; import type { ComponentProps } from "react"; diff --git a/control-plane/web/client/src/components/status/index.ts b/control-plane/web/client/src/components/status/index.ts index cd6ffb23..453dd289 100644 --- a/control-plane/web/client/src/components/status/index.ts +++ b/control-plane/web/client/src/components/status/index.ts @@ -11,4 +11,4 @@ export { } from './StatusBadge'; // Re-export types for convenience -export type { AgentStatus, AgentState, AgentStatusUpdate, StatusSource } from '../../types/brain'; \ No newline at end of file +export type { AgentStatus, AgentState, AgentStatusUpdate, StatusSource } from '../../types/haxen'; \ No newline at end of file diff --git a/control-plane/web/client/src/components/ui/data-formatters.tsx b/control-plane/web/client/src/components/ui/data-formatters.tsx index 10e7aae1..e6420ed4 100644 --- a/control-plane/web/client/src/components/ui/data-formatters.tsx +++ b/control-plane/web/client/src/components/ui/data-formatters.tsx @@ -4,7 +4,7 @@ import { cn } from "../../lib/utils"; /** * Reusable data formatting components for consistent data display - * across the Brain application. These components ensure uniform + * across the Haxen application. These components ensure uniform * formatting of timestamps, durations, file sizes, and other common data types. */ diff --git a/control-plane/web/client/src/components/ui/icon-bridge.tsx b/control-plane/web/client/src/components/ui/icon-bridge.tsx index e51c2a32..62a83ec1 100644 --- a/control-plane/web/client/src/components/ui/icon-bridge.tsx +++ b/control-plane/web/client/src/components/ui/icon-bridge.tsx @@ -10,7 +10,7 @@ import { ArrowsDownUpIcon } from "@phosphor-icons/react/dist/csr/ArrowsDownUp"; import { ArrowsOutSimpleIcon } from "@phosphor-icons/react/dist/csr/ArrowsOutSimple"; import { ArrowsInSimpleIcon } from "@phosphor-icons/react/dist/csr/ArrowsInSimple"; import { CrosshairSimpleIcon } from "@phosphor-icons/react/dist/csr/CrosshairSimple"; -import { BrainIcon } from "@phosphor-icons/react/dist/csr/Brain"; +import { BrainIcon as CognitivePhosphorIcon } from "@phosphor-icons/react/dist/csr/Brain"; import { BracketsCurlyIcon } from "@phosphor-icons/react/dist/csr/BracketsCurly"; import { CornersInIcon } from "@phosphor-icons/react/dist/csr/CornersIn"; import { BroadcastIcon } from "@phosphor-icons/react/dist/csr/Broadcast"; @@ -159,7 +159,8 @@ export const BracketsCurly = BracketsCurlyIcon; export const CornersIn = CornersInIcon; export const Copy = CopySimpleIcon; export const CopySimple = CopySimpleIcon; -export const Cognitive = BrainIcon; +// Phosphor does not expose a dedicated Haxen glyph; reuse the Brain icon asset. +export const Cognitive = CognitivePhosphorIcon; export const DataBase = DatabaseIcon; export const Database = DatabaseIcon; export const ErrorFilled = withDefaults(XCircleIcon, { weight: "fill" }, "ErrorFilled"); @@ -286,7 +287,7 @@ export const WarningAlt = WarningCircleIcon; export const WarningCircle = WarningCircleIcon; export const WarningDiamond = WarningDiamondIcon; export const WarningOctagon = WarningOctagonIcon; -export const WatsonxAi = BrainIcon; +export const WatsonxAi = CognitivePhosphorIcon; export const Wifi = WifiHighIcon; export const WifiOff = WifiSlashIcon; export const Target = TargetIcon; diff --git a/control-plane/web/client/src/components/ui/status-indicator.tsx b/control-plane/web/client/src/components/ui/status-indicator.tsx index 1659f6a8..6b49fbe5 100644 --- a/control-plane/web/client/src/components/ui/status-indicator.tsx +++ b/control-plane/web/client/src/components/ui/status-indicator.tsx @@ -1,6 +1,6 @@ import { cn } from "@/lib/utils"; import React from "react"; -import type { HealthStatus, LifecycleStatus } from "../../types/brain"; +import type { HealthStatus, LifecycleStatus } from "../../types/haxen"; import type { CanonicalStatus } from "../../utils/status"; import { getStatusLabel, getStatusTheme, normalizeExecutionStatus } from "../../utils/status"; diff --git a/control-plane/web/client/src/components/vc/VerifiableCredentialBadge.tsx b/control-plane/web/client/src/components/vc/VerifiableCredentialBadge.tsx index 9d2920d4..2c96cc37 100644 --- a/control-plane/web/client/src/components/vc/VerifiableCredentialBadge.tsx +++ b/control-plane/web/client/src/components/vc/VerifiableCredentialBadge.tsx @@ -276,8 +276,8 @@ function VerificationModal({ )}
- Brain Standard - {verificationResult.compliance_checks.brain_standard_compliance ? ( + Haxen Standard + {verificationResult.compliance_checks.haxen_standard_compliance ? ( ) : ( diff --git a/control-plane/web/client/src/contexts/ModeContext.tsx b/control-plane/web/client/src/contexts/ModeContext.tsx index f5a65102..57bd7959 100644 --- a/control-plane/web/client/src/contexts/ModeContext.tsx +++ b/control-plane/web/client/src/contexts/ModeContext.tsx @@ -18,7 +18,7 @@ interface ModeProviderProps { export function ModeProvider({ children }: ModeProviderProps) { const [mode, setModeState] = useState(() => { // Load mode from localStorage on initialization - const savedMode = localStorage.getItem("brain-app-mode"); + const savedMode = localStorage.getItem("haxen-app-mode"); return savedMode === "developer" || savedMode === "user" ? savedMode : "developer"; @@ -26,7 +26,7 @@ export function ModeProvider({ children }: ModeProviderProps) { const setMode = (newMode: AppMode) => { setModeState(newMode); - localStorage.setItem("brain-app-mode", newMode); + localStorage.setItem("haxen-app-mode", newMode); }; const toggleMode = () => { @@ -36,7 +36,7 @@ export function ModeProvider({ children }: ModeProviderProps) { // Persist mode changes to localStorage useEffect(() => { - localStorage.setItem("brain-app-mode", mode); + localStorage.setItem("haxen-app-mode", mode); }, [mode]); return ( diff --git a/control-plane/web/client/src/hooks/useMCPHealth.ts b/control-plane/web/client/src/hooks/useMCPHealth.ts index c804c8f9..ba70f621 100644 --- a/control-plane/web/client/src/hooks/useMCPHealth.ts +++ b/control-plane/web/client/src/hooks/useMCPHealth.ts @@ -5,7 +5,7 @@ import type { MCPSummaryForUI, MCPHealthEvent, AppMode -} from '../types/brain'; +} from '../types/haxen'; import { getMCPHealthModeAware } from '../services/api'; import { useMode } from '../contexts/ModeContext'; import { useMCPHealthSSE } from './useSSE'; diff --git a/control-plane/web/client/src/hooks/useMCPMetrics.ts b/control-plane/web/client/src/hooks/useMCPMetrics.ts index c3fbeae5..4e29d993 100644 --- a/control-plane/web/client/src/hooks/useMCPMetrics.ts +++ b/control-plane/web/client/src/hooks/useMCPMetrics.ts @@ -3,7 +3,7 @@ import type { MCPServerMetrics, MCPNodeMetrics, MCPServerMetricsResponse -} from '../types/brain'; +} from '../types/haxen'; import { getMCPServerMetrics } from '../services/api'; import { calculatePerformanceMetrics } from '../utils/mcpUtils'; diff --git a/control-plane/web/client/src/hooks/useMCPServers.ts b/control-plane/web/client/src/hooks/useMCPServers.ts index b22f0b6c..c509f463 100644 --- a/control-plane/web/client/src/hooks/useMCPServers.ts +++ b/control-plane/web/client/src/hooks/useMCPServers.ts @@ -3,7 +3,7 @@ import type { MCPServerActionResponse, MCPServerAction, MCPServerHealthForUI -} from '../types/brain'; +} from '../types/haxen'; import { startMCPServer, stopMCPServer, diff --git a/control-plane/web/client/src/hooks/useMCPTools.ts b/control-plane/web/client/src/hooks/useMCPTools.ts index 87875de7..24efa853 100644 --- a/control-plane/web/client/src/hooks/useMCPTools.ts +++ b/control-plane/web/client/src/hooks/useMCPTools.ts @@ -3,7 +3,7 @@ import type { MCPTool, MCPToolsResponse, MCPToolTestResponse -} from '../types/brain'; +} from '../types/haxen'; import { getMCPTools, testMCPTool } from '../services/api'; import { validateToolParameters } from '../utils/mcpUtils'; diff --git a/control-plane/web/client/src/mcp/README.md b/control-plane/web/client/src/mcp/README.md index 76636964..e609e032 100644 --- a/control-plane/web/client/src/mcp/README.md +++ b/control-plane/web/client/src/mcp/README.md @@ -20,22 +20,22 @@ The MCP UI system is built with a modular architecture consisting of: ``` MCP UI System -├── Components (brain/web/client/src/components/mcp/) +├── Components (haxen/web/client/src/components/mcp/) │ ├── MCPHealthIndicator - Status indicators and health displays │ ├── MCPServerCard - Individual server information cards │ ├── MCPServerList - List of all MCP servers │ ├── MCPToolExplorer - Tool discovery and exploration │ ├── MCPToolTester - Interactive tool testing interface │ └── MCPServerControls - Bulk server management controls -├── Hooks (brain/web/client/src/hooks/) +├── Hooks (haxen/web/client/src/hooks/) │ ├── useMCPHealth - Health monitoring and real-time updates │ ├── useMCPServers - Server management operations │ ├── useMCPTools - Tool discovery and execution │ ├── useMCPMetrics - Performance metrics monitoring │ └── useSSE - Server-Sent Events for real-time updates -├── Utilities (brain/web/client/src/utils/) +├── Utilities (haxen/web/client/src/utils/) │ └── mcpUtils - Formatting, validation, and helper functions -└── Integration (brain/web/client/src/mcp/) +└── Integration (haxen/web/client/src/mcp/) └── index.ts - Centralized exports and integration patterns ``` @@ -345,19 +345,19 @@ if (process.env.NODE_ENV === 'development') { ### Adding New Components -1. Create component in `brain/web/client/src/components/mcp/` +1. Create component in `haxen/web/client/src/components/mcp/` 2. Add proper TypeScript types 3. Include accessibility features 4. Add error boundary support -5. Export from `brain/web/client/src/components/mcp/index.ts` +5. Export from `haxen/web/client/src/components/mcp/index.ts` ### Adding New Hooks -1. Create hook in `brain/web/client/src/hooks/` +1. Create hook in `haxen/web/client/src/hooks/` 2. Follow existing patterns for state management 3. Include proper cleanup and error handling 4. Add TypeScript documentation -5. Export from `brain/web/client/src/mcp/index.ts` +5. Export from `haxen/web/client/src/mcp/index.ts` ## API Reference diff --git a/control-plane/web/client/src/mcp/index.ts b/control-plane/web/client/src/mcp/index.ts index bf585259..09ef048c 100644 --- a/control-plane/web/client/src/mcp/index.ts +++ b/control-plane/web/client/src/mcp/index.ts @@ -123,4 +123,4 @@ export type { MCPHealthResponseUser, MCPHealthResponseDeveloper, AppMode -} from '../types/brain'; +} from '../types/haxen'; diff --git a/control-plane/web/client/src/pages/ExecutionDetailPage.tsx b/control-plane/web/client/src/pages/ExecutionDetailPage.tsx index 00e7c854..dfaafe96 100644 --- a/control-plane/web/client/src/pages/ExecutionDetailPage.tsx +++ b/control-plane/web/client/src/pages/ExecutionDetailPage.tsx @@ -224,9 +224,9 @@ export function ExecutionDetailPage() { onClick={execution.session_id ? navigateToSession : undefined} /> { const [selectedPackage, setSelectedPackage] = useState( diff --git a/control-plane/web/client/src/services/api.ts b/control-plane/web/client/src/services/api.ts index 54c101c4..a8058acd 100644 --- a/control-plane/web/client/src/services/api.ts +++ b/control-plane/web/client/src/services/api.ts @@ -19,7 +19,7 @@ import type { ConfigSchemaResponse, AgentStatus, AgentStatusUpdate -} from '../types/brain'; +} from '../types/haxen'; const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '/api/ui/v1'; diff --git a/control-plane/web/client/src/services/configurationApi.ts b/control-plane/web/client/src/services/configurationApi.ts index 4096245e..afbad36e 100644 --- a/control-plane/web/client/src/services/configurationApi.ts +++ b/control-plane/web/client/src/services/configurationApi.ts @@ -1,4 +1,4 @@ -import type { ConfigurationSchema, AgentConfiguration, AgentPackage, AgentLifecycleInfo } from '../types/brain'; +import type { ConfigurationSchema, AgentConfiguration, AgentPackage, AgentLifecycleInfo } from '../types/haxen'; const API_BASE = '/api/ui/v1'; diff --git a/control-plane/web/client/src/services/executionsApi.ts b/control-plane/web/client/src/services/executionsApi.ts index 7fc8a6f4..68e4dbd3 100644 --- a/control-plane/web/client/src/services/executionsApi.ts +++ b/control-plane/web/client/src/services/executionsApi.ts @@ -155,7 +155,7 @@ function transformExecutionDetailsResponse(raw: any): WorkflowExecution { id: raw.id, workflow_id: raw.workflow_id, execution_id: raw.execution_id, - brain_request_id: raw.brain_request_id ?? "", + haxen_request_id: raw.haxen_request_id ?? "", session_id: raw.session_id ?? undefined, actor_id: raw.actor_id ?? undefined, agent_node_id: raw.agent_node_id, diff --git a/control-plane/web/client/src/services/searchService.ts b/control-plane/web/client/src/services/searchService.ts index 419a5836..383c23fe 100644 --- a/control-plane/web/client/src/services/searchService.ts +++ b/control-plane/web/client/src/services/searchService.ts @@ -1,5 +1,5 @@ import { getNodesSummary } from './api'; -import type { AgentNodeSummary } from '../types/brain'; +import type { AgentNodeSummary } from '../types/haxen'; export interface SearchResult { id: string; diff --git a/control-plane/web/client/src/types/did.ts b/control-plane/web/client/src/types/did.ts index 770e7b42..555780f6 100644 --- a/control-plane/web/client/src/types/did.ts +++ b/control-plane/web/client/src/types/did.ts @@ -3,7 +3,7 @@ export interface AgentDIDInfo { did: string; agent_node_id: string; - brain_server_id: string; + haxen_server_id: string; public_key_jwk: any; derivation_path: string; reasoners: Record; @@ -76,7 +76,7 @@ export interface DIDIdentityPackage { agent_did: DIDIdentity; reasoner_dids: Record; skill_dids: Record; - brain_server_id: string; + haxen_server_id: string; } export interface DIDIdentity { @@ -222,7 +222,7 @@ export interface SecurityAnalysis { export interface ComplianceChecks { w3c_compliance: boolean; - brain_standard_compliance: boolean; + haxen_standard_compliance: boolean; audit_trail_integrity: boolean; data_integrity_checks: boolean; issues: VerificationIssue[]; @@ -265,7 +265,7 @@ export interface DIDResolutionEntry { } export interface DIDFilters { - brain_server_id?: string; + haxen_server_id?: string; agent_node_id?: string; component_type?: string; status?: AgentDIDStatus; diff --git a/control-plane/web/client/src/types/executions.ts b/control-plane/web/client/src/types/executions.ts index fd692156..92ced2a7 100644 --- a/control-plane/web/client/src/types/executions.ts +++ b/control-plane/web/client/src/types/executions.ts @@ -98,7 +98,7 @@ export interface WorkflowExecution { id: number; workflow_id: string; execution_id: string; - brain_request_id: string; + haxen_request_id: string; session_id?: string; actor_id?: string; agent_node_id: string; diff --git a/control-plane/web/client/src/types/brain.ts b/control-plane/web/client/src/types/haxen.ts similarity index 100% rename from control-plane/web/client/src/types/brain.ts rename to control-plane/web/client/src/types/haxen.ts diff --git a/control-plane/web/client/src/utils/mcpUtils.ts b/control-plane/web/client/src/utils/mcpUtils.ts index 94aebfe9..d08c7e15 100644 --- a/control-plane/web/client/src/utils/mcpUtils.ts +++ b/control-plane/web/client/src/utils/mcpUtils.ts @@ -5,7 +5,7 @@ import type { MCPServerStatus, MCPHealthEvent, AppMode -} from '../types/brain'; +} from '../types/haxen'; /** * Status color mapping for MCP servers diff --git a/control-plane/web/client/src/utils/node-status.ts b/control-plane/web/client/src/utils/node-status.ts index 6b96a767..35286a1c 100644 --- a/control-plane/web/client/src/utils/node-status.ts +++ b/control-plane/web/client/src/utils/node-status.ts @@ -2,7 +2,7 @@ import type { AgentNodeSummary, HealthStatus, LifecycleStatus, -} from "@/types/brain"; +} from "@/types/haxen"; import { getStatusTheme, type CanonicalStatus, diff --git a/control-plane/web/client/ui_embed.go b/control-plane/web/client/ui_embed.go index ba75e33b..6a67b50f 100644 --- a/control-plane/web/client/ui_embed.go +++ b/control-plane/web/client/ui_embed.go @@ -1,4 +1,4 @@ -// UI embedding and route registration for Brain +// UI embedding and route registration for Haxen package client diff --git a/deployments/docker/Dockerfile.control-plane b/deployments/docker/Dockerfile.control-plane index 32b4820d..cddbe7a0 100644 --- a/deployments/docker/Dockerfile.control-plane +++ b/deployments/docker/Dockerfile.control-plane @@ -17,10 +17,10 @@ COPY control-plane/ ./control-plane/ COPY --from=ui-builder /app/web/dist ./control-plane/web/client/dist RUN --mount=type=cache,target=/root/.cache/go-build --mount=type=cache,target=/go/pkg/mod \ - cd control-plane && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o /app/bin/brain-server ./cmd/brain-server + cd control-plane && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o /app/bin/haxen-server ./cmd/haxen-server FROM gcr.io/distroless/base-debian12 -COPY --from=go-builder /app/bin/brain-server /usr/local/bin/brain-server -COPY --from=go-builder /app/control-plane/config /etc/brain/config +COPY --from=go-builder /app/bin/haxen-server /usr/local/bin/haxen-server +COPY --from=go-builder /app/control-plane/config /etc/haxen/config USER nonroot:nonroot -ENTRYPOINT ["/usr/local/bin/brain-server"] +ENTRYPOINT ["/usr/local/bin/haxen-server"] diff --git a/deployments/docker/Dockerfile.go-agent b/deployments/docker/Dockerfile.go-agent index fc0f77bb..eee342fc 100644 --- a/deployments/docker/Dockerfile.go-agent +++ b/deployments/docker/Dockerfile.go-agent @@ -9,4 +9,4 @@ RUN --mount=type=cache,target=/root/.cache/go-build --mount=type=cache,target=/g ENV GO111MODULE=on -CMD ["sh", "-c", "echo 'Brain Go agent image ready. Mount or COPY your agent source and override CMD to run it.' && tail -f /dev/null"] +CMD ["sh", "-c", "echo 'Haxen Go agent image ready. Mount or COPY your agent source and override CMD to run it.' && tail -f /dev/null"] diff --git a/deployments/docker/Dockerfile.python-agent b/deployments/docker/Dockerfile.python-agent index 7004fc5d..7892a408 100644 --- a/deployments/docker/Dockerfile.python-agent +++ b/deployments/docker/Dockerfile.python-agent @@ -11,4 +11,4 @@ RUN pip install --no-cache-dir --upgrade pip && \ pip install --no-cache-dir /tmp/python-sdk && \ rm -rf /tmp/python-sdk -CMD ["python", "-c", "print('Brain Python agent image ready. Override CMD to run your agent.')"] +CMD ["python", "-c", "print('Haxen Python agent image ready. Override CMD to run your agent.')"] diff --git a/deployments/docker/README.md b/deployments/docker/README.md index 6b0e70bf..8275b4b1 100644 --- a/deployments/docker/README.md +++ b/deployments/docker/README.md @@ -1,4 +1,4 @@ -# Brain Docker Deployments +# Haxen Docker Deployments This directory contains reference Dockerfiles and a Compose stack for local development. diff --git a/deployments/docker/docker-compose.yml b/deployments/docker/docker-compose.yml index 4176dd76..9d1562de 100644 --- a/deployments/docker/docker-compose.yml +++ b/deployments/docker/docker-compose.yml @@ -5,9 +5,9 @@ services: image: postgres:15-alpine restart: unless-stopped environment: - POSTGRES_USER: brain - POSTGRES_PASSWORD: brain - POSTGRES_DB: brain + POSTGRES_USER: haxen + POSTGRES_PASSWORD: haxen + POSTGRES_DB: haxen volumes: - pgdata:/var/lib/postgresql/data @@ -17,9 +17,9 @@ services: context: ../.. dockerfile: deployments/docker/Dockerfile.control-plane environment: - BRAIN_DATABASE_URL: postgres://brain:brain@postgres:5432/brain?sslmode=disable - BRAIN_REDIS_URL: redis://redis:6379/0 - BRAIN_HTTP_ADDR: 0.0.0.0:8080 + HAXEN_DATABASE_URL: postgres://haxen:haxen@postgres:5432/haxen?sslmode=disable + HAXEN_REDIS_URL: redis://redis:6379/0 + HAXEN_HTTP_ADDR: 0.0.0.0:8080 ports: - "8080:8080" depends_on: diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index d769e175..cf3b4638 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,6 +1,6 @@ -# Brain Architecture +# Haxen Architecture -Brain provides a modular platform for orchestrating AI agents. The system is composed of a Go-based control plane, SDKs for client languages, and optional runtime services. +Haxen provides a modular platform for orchestrating AI agents. The system is composed of a Go-based control plane, SDKs for client languages, and optional runtime services. ## High-Level Overview diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index ee465d22..f9e807b1 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -1,6 +1,6 @@ # Contributing Guide -Thank you for your interest in contributing to Brain! This guide outlines how to propose changes, report issues, and participate in the community. +Thank you for your interest in contributing to Haxen! This guide outlines how to propose changes, report issues, and participate in the community. ## Ground Rules diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 5f98b997..01002f94 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -1,6 +1,6 @@ # Development Guide -This document provides instructions for working on the Brain monorepo locally. +This document provides instructions for working on the Haxen monorepo locally. ## Prerequisites @@ -12,8 +12,8 @@ This document provides instructions for working on the Brain monorepo locally. ## Initial Setup ```bash -git clone https://github.com/your-org/brain.git -cd brain +git clone https://github.com/your-org/haxen.git +cd haxen ./scripts/install.sh ``` @@ -47,16 +47,16 @@ The install script performs: Copy `control-plane/config/.env.example` to `.env` (if available) and adjust: -- `BRAIN_DATABASE_URL` — PostgreSQL connection string. -- `BRAIN_REDIS_URL` — Redis instance used for queues. -- `BRAIN_JWT_SECRET` — Authentication secret (development only). +- `HAXEN_DATABASE_URL` — PostgreSQL connection string. +- `HAXEN_REDIS_URL` — Redis instance used for queues. +- `HAXEN_JWT_SECRET` — Authentication secret (development only). ## Database Migrations ```bash cd control-plane -goose -dir ./migrations postgres "$BRAIN_DATABASE_URL" status -goose -dir ./migrations postgres "$BRAIN_DATABASE_URL" up +goose -dir ./migrations postgres "$HAXEN_DATABASE_URL" status +goose -dir ./migrations postgres "$HAXEN_DATABASE_URL" up ``` ## Frontend Development diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 4933ce38..e820fb6d 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -1,13 +1,13 @@ -# Releasing Brain +# Releasing Haxen -This guide explains how maintainers publish new versions of the Brain control plane, SDKs, and container images. +This guide explains how maintainers publish new versions of the Haxen control plane, SDKs, and container images. ## Versioning - Tag releases with semantic versions: `vMAJOR.MINOR.PATCH`. - The tag drives the automation. Tagging `main` (or dispatching the workflow manually) kicks off Go binary builds, Python package publishing, and Docker image pushes. - Update component versions before tagging: - - `sdk/python/pyproject.toml` & `sdk/python/brain_sdk/__init__.py` + - `sdk/python/pyproject.toml` & `sdk/python/haxen_sdk/__init__.py` - Release notes in `CHANGELOG.md` ## Required Secrets @@ -35,11 +35,11 @@ What happens: 3. Build the control plane UI (`npm install && npm run build`). 4. Run [GoReleaser](https://goreleaser.com) using `.goreleaser.yml` to produce multi-platform binaries and attach them to the GitHub release. 5. Build the Python SDK (`python -m build`) and, if enabled, publish to PyPI with `twine upload`. -6. Build and push the `Dockerfile.control-plane` image (defaults to `ghcr.io//brain-control-plane:`). +6. Build and push the `Dockerfile.control-plane` image (defaults to `ghcr.io//haxen-control-plane:`). Artifacts: -- Release binaries (`brain-server` for Linux/Darwin/Windows, amd64/arm64). +- Release binaries (`haxen-server` for Linux/Darwin/Windows, amd64/arm64). - Python SDK wheel & sdist on PyPI (and attached to the release for manual runs). - Multi-architecture Docker image. @@ -54,9 +54,9 @@ Use `workflow_dispatch` to stage a release without pushing external artifacts: ## Testing Release Artifacts -- **Go binaries**: download from the release page or workflow artifacts and run `brain-server --help`. Cross-platform builds are generated for Linux (amd64/arm64), Darwin (amd64/arm64), and Windows (amd64). -- **Python package**: install locally via `pip install --index-url https://test.pypi.org/simple brain-sdk` if you push to TestPyPI first, or install from the generated wheel. -- **Docker image**: `docker run --rm ghcr.io//brain-control-plane: --help`. +- **Go binaries**: download from the release page or workflow artifacts and run `haxen-server --help`. Cross-platform builds are generated for Linux (amd64/arm64), Darwin (amd64/arm64), and Windows (amd64). +- **Python package**: install locally via `pip install --index-url https://test.pypi.org/simple haxen-sdk` if you push to TestPyPI first, or install from the generated wheel. +- **Docker image**: `docker run --rm ghcr.io//haxen-control-plane: --help`. ## Emergency Fixes diff --git a/sdk/go/README.md b/sdk/go/README.md index e5f1c6fe..b44e7637 100644 --- a/sdk/go/README.md +++ b/sdk/go/README.md @@ -1,11 +1,11 @@ -# Brain Go SDK +# Haxen Go SDK -The Brain Go SDK provides idiomatic Go bindings for interacting with the Brain control plane. +The Haxen Go SDK provides idiomatic Go bindings for interacting with the Haxen control plane. ## Installation ```bash -go get github.com/your-org/brain/sdk/go +go get github.com/your-org/haxen/sdk/go ``` ## Quick Start @@ -17,13 +17,13 @@ import ( "context" "log" - brainagent "github.com/your-org/brain/sdk/go/agent" + haxenagent "github.com/your-org/haxen/sdk/go/agent" ) func main() { - agent, err := brainagent.New(brainagent.Config{ + agent, err := haxenagent.New(haxenagent.Config{ NodeID: "example-agent", - BrainURL: "http://localhost:8080", + HaxenURL: "http://localhost:8080", }) if err != nil { log.Fatal(err) @@ -41,8 +41,8 @@ func main() { ## Modules -- `agent`: Build Brain-compatible agents and register reasoners/skills. -- `client`: Low-level HTTP client for the Brain control plane. +- `agent`: Build Haxen-compatible agents and register reasoners/skills. +- `client`: Low-level HTTP client for the Haxen control plane. - `types`: Shared data structures and contracts. - `ai`: Helpers for interacting with AI providers via the control plane. diff --git a/sdk/go/agent/agent.go b/sdk/go/agent/agent.go index b16bccf4..62d798e4 100644 --- a/sdk/go/agent/agent.go +++ b/sdk/go/agent/agent.go @@ -17,14 +17,14 @@ import ( "syscall" "time" - "github.com/your-org/brain/sdk/go/ai" - "github.com/your-org/brain/sdk/go/client" - "github.com/your-org/brain/sdk/go/types" + "github.com/your-org/haxen/sdk/go/ai" + "github.com/your-org/haxen/sdk/go/client" + "github.com/your-org/haxen/sdk/go/types" ) type executionContextKey struct{} -// ExecutionContext captures the headers Brain sends with each execution request. +// ExecutionContext captures the headers Haxen sends with each execution request. type ExecutionContext struct { RunID string ExecutionID string @@ -74,7 +74,7 @@ type Config struct { NodeID string Version string TeamID string - BrainURL string + HaxenURL string ListenAddress string PublicURL string Token string @@ -121,8 +121,8 @@ func New(cfg Config) (*Agent, error) { if cfg.TeamID == "" { cfg.TeamID = "default" } - if cfg.BrainURL == "" { - return nil, errors.New("config.BrainURL is required") + if cfg.HaxenURL == "" { + return nil, errors.New("config.HaxenURL is required") } if cfg.ListenAddress == "" { cfg.ListenAddress = ":8001" @@ -141,7 +141,7 @@ func New(cfg Config) (*Agent, error) { Timeout: 15 * time.Second, } - c, err := client.New(cfg.BrainURL, client.WithHTTPClient(httpClient), client.WithBearerToken(cfg.Token)) + c, err := client.New(cfg.HaxenURL, client.WithHTTPClient(httpClient), client.WithBearerToken(cfg.Token)) if err != nil { return nil, err } @@ -203,7 +203,7 @@ func (a *Agent) RegisterReasoner(name string, handler HandlerFunc, opts ...Reaso a.reasoners[name] = meta } -// Initialize registers the agent with the Brain control plane without starting a listener. +// Initialize registers the agent with the Haxen control plane without starting a listener. func (a *Agent) Initialize(ctx context.Context) error { a.initMu.Lock() defer a.initMu.Unlock() @@ -295,7 +295,7 @@ func (a *Agent) registerNode(ctx context.Context) error { return err } - a.logger.Printf("node %s registered with Brain", a.cfg.NodeID) + a.logger.Printf("node %s registered with Haxen", a.cfg.NodeID) return nil } @@ -399,7 +399,7 @@ func (a *Agent) handleReasoner(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, result) } -// Call invokes another reasoner via the Brain control plane, preserving execution context. +// Call invokes another reasoner via the Haxen control plane, preserving execution context. func (a *Agent) Call(ctx context.Context, target string, input map[string]any) (map[string]any, error) { if !strings.Contains(target, ".") { target = fmt.Sprintf("%s.%s", a.cfg.NodeID, strings.TrimPrefix(target, ".")) @@ -417,7 +417,7 @@ func (a *Agent) Call(ctx context.Context, target string, input map[string]any) ( return nil, fmt.Errorf("marshal call payload: %w", err) } - url := fmt.Sprintf("%s/api/v1/execute/%s", strings.TrimSuffix(a.cfg.BrainURL, "/"), strings.TrimPrefix(target, "/")) + url := fmt.Sprintf("%s/api/v1/execute/%s", strings.TrimSuffix(a.cfg.HaxenURL, "/"), strings.TrimPrefix(target, "/")) req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if err != nil { return nil, fmt.Errorf("build request: %w", err) diff --git a/sdk/go/ai/README.md b/sdk/go/ai/README.md index 2f0a0b5f..a47ce746 100644 --- a/sdk/go/ai/README.md +++ b/sdk/go/ai/README.md @@ -1,6 +1,6 @@ # Go SDK AI Package -This package provides AI/LLM capabilities for the Brain Go SDK, supporting both OpenAI and OpenRouter APIs with structured output support. +This package provides AI/LLM capabilities for the Haxen Go SDK, supporting both OpenAI and OpenRouter APIs with structured output support. ## Features @@ -18,8 +18,8 @@ This package provides AI/LLM capabilities for the Brain Go SDK, supporting both ```go import ( "context" - "github.com/your-org/brain/sdk/go/agent" - "github.com/your-org/brain/sdk/go/ai" + "github.com/your-org/haxen/sdk/go/agent" + "github.com/your-org/haxen/sdk/go/ai" ) // Create agent with AI configured @@ -27,7 +27,7 @@ aiConfig := ai.DefaultConfig() // Reads from env vars agent, err := agent.New(agent.Config{ NodeID: "my-agent", Version: "1.0.0", - BrainURL: "http://localhost:8080", + HaxenURL: "http://localhost:8080", AIConfig: aiConfig, }) diff --git a/sdk/go/client/client.go b/sdk/go/client/client.go index f8552f8d..6c4b75dc 100644 --- a/sdk/go/client/client.go +++ b/sdk/go/client/client.go @@ -12,10 +12,10 @@ import ( "strings" "time" - "github.com/your-org/brain/sdk/go/types" + "github.com/your-org/haxen/sdk/go/types" ) -// Client provides a thin wrapper over the Brain control plane REST API. +// Client provides a thin wrapper over the Haxen control plane REST API. type Client struct { baseURL *url.URL httpClient *http.Client @@ -193,12 +193,12 @@ func (c *Client) legacyHeartbeat(ctx context.Context, nodeID string, payload typ }, nil } -// APIError captures non-success responses from the Brain API. +// APIError captures non-success responses from the Haxen API. type APIError struct { StatusCode int Body []byte } func (e *APIError) Error() string { - return fmt.Sprintf("brain api error (%d): %s", e.StatusCode, strings.TrimSpace(string(e.Body))) + return fmt.Sprintf("haxen api error (%d): %s", e.StatusCode, strings.TrimSpace(string(e.Body))) } diff --git a/sdk/go/go.mod b/sdk/go/go.mod index 61a5f7e5..bc5f4ba2 100644 --- a/sdk/go/go.mod +++ b/sdk/go/go.mod @@ -1,3 +1,3 @@ -module github.com/your-org/brain/sdk/go +module github.com/your-org/haxen/sdk/go go 1.21 diff --git a/sdk/go/types/types.go b/sdk/go/types/types.go index 979de47f..d67e2f24 100644 --- a/sdk/go/types/types.go +++ b/sdk/go/types/types.go @@ -5,7 +5,7 @@ import ( "time" ) -// ReasonerDefinition mirrors the Brain server registration contract. +// ReasonerDefinition mirrors the Haxen server registration contract. type ReasonerDefinition struct { ID string `json:"id"` InputSchema json.RawMessage `json:"input_schema"` diff --git a/sdk/python/CHANGELOG.md b/sdk/python/CHANGELOG.md index a6735560..9b65c3aa 100644 --- a/sdk/python/CHANGELOG.md +++ b/sdk/python/CHANGELOG.md @@ -1,5 +1,5 @@ # Changelog ## [0.1.0] - 2024-XX-XX -- Initial public release of the Brain Python SDK. +- Initial public release of the Haxen Python SDK. - Provides agent runtime, workflow helpers, async execution, and credential tooling. diff --git a/sdk/python/MANIFEST.in b/sdk/python/MANIFEST.in index 6ee109c4..8593f925 100644 --- a/sdk/python/MANIFEST.in +++ b/sdk/python/MANIFEST.in @@ -1,7 +1,7 @@ include README.md include LICENSE include requirements.txt -recursive-include brain_sdk *.py +recursive-include haxen_sdk *.py exclude examples/* exclude tests/* global-exclude *.pyc diff --git a/sdk/python/README.md b/sdk/python/README.md index f52b25b4..783c0944 100644 --- a/sdk/python/README.md +++ b/sdk/python/README.md @@ -1,29 +1,29 @@ -# Brain Python SDK +# Haxen Python SDK -The Brain SDK provides a production-ready Python interface for registering agents, executing workflows, and integrating with the Brain control plane. +The Haxen SDK provides a production-ready Python interface for registering agents, executing workflows, and integrating with the Haxen control plane. ## Installation ```bash -pip install brain-sdk +pip install haxen-sdk ``` To work on the SDK locally: ```bash -git clone https://github.com/your-org/brain.git -cd brain/sdk/python +git clone https://github.com/your-org/haxen.git +cd haxen/sdk/python python -m pip install -e .[dev] ``` ## Quick Start ```python -from brain_sdk import Agent +from haxen_sdk import Agent agent = Agent( node_id="example-agent", - brain_server="http://localhost:8080", + haxen_server="http://localhost:8080", dev_mode=True, ) @@ -50,7 +50,7 @@ pytest To run coverage locally: ```bash -pytest --cov=brain_sdk --cov-report=term-missing +pytest --cov=haxen_sdk --cov-report=term-missing ``` ## License diff --git a/sdk/python/brain_sdk/.DS_Store b/sdk/python/haxen_sdk/.DS_Store similarity index 100% rename from sdk/python/brain_sdk/.DS_Store rename to sdk/python/haxen_sdk/.DS_Store diff --git a/sdk/python/brain_sdk/README_stdio_bridge.md b/sdk/python/haxen_sdk/README_stdio_bridge.md similarity index 96% rename from sdk/python/brain_sdk/README_stdio_bridge.md rename to sdk/python/haxen_sdk/README_stdio_bridge.md index c0d36589..18202f36 100644 --- a/sdk/python/brain_sdk/README_stdio_bridge.md +++ b/sdk/python/haxen_sdk/README_stdio_bridge.md @@ -4,7 +4,7 @@ The `mcp_stdio_bridge.py` module provides a bridge that converts stdio-based MCP ## Overview -Some MCP servers (like `@modelcontextprotocol/server-sequential-thinking`) use stdio transport instead of HTTP. The current Brain SDK implementation assumes all servers are HTTP-based, causing failures when trying to communicate with stdio servers. This bridge solves that problem. +Some MCP servers (like `@modelcontextprotocol/server-sequential-thinking`) use stdio transport instead of HTTP. The current Haxen SDK implementation assumes all servers are HTTP-based, causing failures when trying to communicate with stdio servers. This bridge solves that problem. ## How It Works @@ -28,7 +28,7 @@ Some MCP servers (like `@modelcontextprotocol/server-sequential-thinking`) use s ```python import asyncio -from brain_sdk.mcp_stdio_bridge import StdioMCPBridge +from haxen_sdk.mcp_stdio_bridge import StdioMCPBridge async def main(): # Configure your stdio MCP server @@ -95,8 +95,8 @@ async def test_bridge(): The bridge is designed to work seamlessly with the existing `MCPClient`: ```python -from brain_sdk.mcp_client import MCPClient -from brain_sdk.mcp_stdio_bridge import StdioMCPBridge +from haxen_sdk.mcp_client import MCPClient +from haxen_sdk.mcp_stdio_bridge import StdioMCPBridge # Start the bridge bridge = StdioMCPBridge(server_config, port=8200) diff --git a/sdk/python/brain_sdk/__init__.py b/sdk/python/haxen_sdk/__init__.py similarity index 100% rename from sdk/python/brain_sdk/__init__.py rename to sdk/python/haxen_sdk/__init__.py diff --git a/sdk/python/brain_sdk/agent.py b/sdk/python/haxen_sdk/agent.py similarity index 94% rename from sdk/python/brain_sdk/agent.py rename to sdk/python/haxen_sdk/agent.py index 7ad3d0c0..9cc44b46 100644 --- a/sdk/python/brain_sdk/agent.py +++ b/sdk/python/haxen_sdk/agent.py @@ -20,29 +20,29 @@ Dict, Literal, ) -from brain_sdk.agent_ai import AgentAI -from brain_sdk.agent_brain import AgentBrain -from brain_sdk.agent_mcp import AgentMCP -from brain_sdk.agent_registry import clear_current_agent, set_current_agent -from brain_sdk.agent_server import AgentServer -from brain_sdk.agent_workflow import AgentWorkflow -from brain_sdk.client import BrainClient -from brain_sdk.dynamic_skills import DynamicMCPSkillManager -from brain_sdk.execution_context import ExecutionContext, get_current_context -from brain_sdk.did_manager import DIDManager -from brain_sdk.vc_generator import VCGenerator -from brain_sdk.mcp_client import MCPClientRegistry -from brain_sdk.mcp_manager import MCPManager -from brain_sdk.memory import MemoryClient, MemoryInterface -from brain_sdk.memory_events import MemoryEventClient -from brain_sdk.logger import log_debug, log_error, log_info, log_warn -from brain_sdk.router import AgentRouter -from brain_sdk.connection_manager import ConnectionManager -from brain_sdk.types import AgentStatus, AIConfig, MemoryConfig -from brain_sdk.multimodal_response import MultimodalResponse -from brain_sdk.async_config import AsyncConfig -from brain_sdk.async_execution_manager import AsyncExecutionManager -from brain_sdk.pydantic_utils import convert_function_args, should_convert_args +from haxen_sdk.agent_ai import AgentAI +from haxen_sdk.agent_haxen import AgentHaxen +from haxen_sdk.agent_mcp import AgentMCP +from haxen_sdk.agent_registry import clear_current_agent, set_current_agent +from haxen_sdk.agent_server import AgentServer +from haxen_sdk.agent_workflow import AgentWorkflow +from haxen_sdk.client import HaxenClient +from haxen_sdk.dynamic_skills import DynamicMCPSkillManager +from haxen_sdk.execution_context import ExecutionContext, get_current_context +from haxen_sdk.did_manager import DIDManager +from haxen_sdk.vc_generator import VCGenerator +from haxen_sdk.mcp_client import MCPClientRegistry +from haxen_sdk.mcp_manager import MCPManager +from haxen_sdk.memory import MemoryClient, MemoryInterface +from haxen_sdk.memory_events import MemoryEventClient +from haxen_sdk.logger import log_debug, log_error, log_info, log_warn +from haxen_sdk.router import AgentRouter +from haxen_sdk.connection_manager import ConnectionManager +from haxen_sdk.types import AgentStatus, AIConfig, MemoryConfig +from haxen_sdk.multimodal_response import MultimodalResponse +from haxen_sdk.async_config import AsyncConfig +from haxen_sdk.async_execution_manager import AsyncExecutionManager +from haxen_sdk.pydantic_utils import convert_function_args, should_convert_args from fastapi import FastAPI, Request, HTTPException from pydantic import create_model, BaseModel, ValidationError @@ -294,15 +294,15 @@ def _resolve_callback_url(callback_url: Optional[str], port: int) -> str: class Agent(FastAPI): """ - Brain Agent - FastAPI subclass for creating AI agent nodes. + Haxen Agent - FastAPI subclass for creating AI agent nodes. - The Agent class is the core component of the Brain SDK that enables developers to create + The Agent class is the core component of the Haxen SDK that enables developers to create intelligent agent nodes. It inherits from FastAPI to provide HTTP endpoints and integrates - with the Brain ecosystem for distributed AI workflows. + with the Haxen ecosystem for distributed AI workflows. Key Features: - Decorator-based reasoner and skill registration - - Cross-agent communication via the Brain execution gateway + - Cross-agent communication via the Haxen execution gateway - Memory interface for persistent and session-based storage - MCP (Model Context Protocol) server integration - Automatic workflow tracking and DAG building @@ -310,12 +310,12 @@ class Agent(FastAPI): Example: ```python - from brain_sdk import Agent + from haxen_sdk import Agent # Create an agent instance app = Agent( node_id="my_agent", - brain_server="http://localhost:8080" + haxen_server="http://localhost:8080" ) # Define a reasoner (AI-powered function) @@ -341,7 +341,7 @@ def format_response(sentiment: str, confidence: float) -> str: def __init__( self, node_id: str, - brain_server: str = "http://localhost:8080", + haxen_server: str = "http://localhost:8080", version: str = "1.0.0", ai_config: Optional[AIConfig] = None, memory_config: Optional[MemoryConfig] = None, @@ -352,25 +352,25 @@ def __init__( **kwargs, ): """ - Initialize a new Brain Agent instance. + Initialize a new Haxen Agent instance. Sets log level to DEBUG if dev_mode is True, else INFO. """ # Set logging level based on dev_mode - from brain_sdk.logger import set_log_level + from haxen_sdk.logger import set_log_level set_log_level("DEBUG" if dev_mode else "INFO") """ Creates a new agent node that can host reasoners (AI-powered functions) and skills - (deterministic functions) while integrating with the Brain ecosystem for distributed + (deterministic functions) while integrating with the Haxen ecosystem for distributed AI workflows and cross-agent communication. Args: node_id (str): Unique identifier for this agent node. Used for routing and cross-agent communication. Should be descriptive and unique - within your Brain ecosystem. - brain_server (str, optional): URL of the Brain server for registration and + within your Haxen ecosystem. + haxen_server (str, optional): URL of the Haxen server for registration and execution gateway. Defaults to "http://localhost:8080". version (str, optional): Version string for this agent. Used for compatibility checking and deployment tracking. Defaults to "1.0.0". @@ -382,7 +382,7 @@ def __init__( dev_mode (bool, optional): Enable development mode with verbose logging and debugging features. Defaults to False. async_config (AsyncConfig, optional): Configuration for async execution behavior. - callback_url (str, optional): Explicit callback URL for Brain server to reach this agent. + callback_url (str, optional): Explicit callback URL for Haxen server to reach this agent. If not provided, will use AGENT_CALLBACK_URL environment variable, auto-detection for containers, or fallback to localhost. **kwargs: Additional keyword arguments passed to FastAPI constructor. @@ -395,7 +395,7 @@ def __init__( # Advanced configuration app = Agent( node_id="advanced_agent", - brain_server="https://brain.company.com", + haxen_server="https://haxen.company.com", version="2.1.0", ai_config=AIConfig( provider="openai", @@ -419,7 +419,7 @@ def __init__( super().__init__(**kwargs) self.node_id = node_id - self.brain_server = brain_server + self.haxen_server = haxen_server self.version = version self.reasoners = [] self.skills = [] @@ -431,7 +431,7 @@ def __init__( self._heartbeat_thread = None self._heartbeat_stop_event = threading.Event() self.dev_mode = dev_mode - self.brain_connected = False + self.haxen_connected = False self.auto_register = ( auto_register # Auto-register on first invocation (serverless mode) ) @@ -447,8 +447,8 @@ def __init__( # Initialize async configuration self.async_config = async_config or AsyncConfig.from_environment() - # Initialize BrainClient with async configuration - self.client = BrainClient(base_url=brain_server, async_config=self.async_config) + # Initialize HaxenClient with async configuration + self.client = HaxenClient(base_url=haxen_server, async_config=self.async_config) self._current_execution_context: Optional[ExecutionContext] = None # Initialize async execution manager (will be lazily created when needed) @@ -481,13 +481,13 @@ def __init__( self.vc_generator: Optional[VCGenerator] = None self.did_enabled = False - # Add connection management for resilient Brain server connectivity + # Add connection management for resilient Haxen server connectivity self.connection_manager: Optional[ConnectionManager] = None # Initialize handlers self.ai_handler = AgentAI(self) self.mcp_handler = AgentMCP(self) - self.brain_handler = AgentBrain(self) + self.haxen_handler = AgentHaxen(self) self.workflow_handler = AgentWorkflow(self) self.server_handler = AgentServer(self) @@ -519,8 +519,8 @@ def __init__( # Initialize DID components self._initialize_did_system() - # Setup standard Brain routes and memory event listeners - self.server_handler.setup_brain_routes() + # Setup standard Haxen routes and memory event listeners + self.server_handler.setup_haxen_routes() self._register_memory_event_listeners() # Register this agent instance for automatic workflow tracking @@ -528,7 +528,7 @@ def __init__( # Limit concurrent outbound calls to avoid overloading the local runtime. default_limit = max(1, min(self.async_config.connection_pool_size, 256)) - max_calls_env = os.getenv("BRAIN_AGENT_MAX_CONCURRENT_CALLS") + max_calls_env = os.getenv("HAXEN_AGENT_MAX_CONCURRENT_CALLS") if max_calls_env: try: parsed_limit = int(max_calls_env) @@ -536,7 +536,7 @@ def __init__( except ValueError: self._max_concurrent_calls = default_limit log_warn( - f"Invalid BRAIN_AGENT_MAX_CONCURRENT_CALLS='{max_calls_env}', defaulting to {default_limit}" + f"Invalid HAXEN_AGENT_MAX_CONCURRENT_CALLS='{max_calls_env}', defaulting to {default_limit}" ) else: self._max_concurrent_calls = default_limit @@ -553,7 +553,7 @@ def handle_serverless(self, event: dict) -> dict: and returns the result. Special Endpoints: - - /discover: Returns agent metadata for Brain server registration + - /discover: Returns agent metadata for Haxen server registration - /execute: Executes reasoners and skills Args: @@ -569,7 +569,7 @@ def handle_serverless(self, event: dict) -> dict: Example: ```python # AWS Lambda handler with API Gateway - from brain_sdk import Agent + from haxen_sdk import Agent app = Agent("my_agent", auto_register=False) @@ -589,15 +589,15 @@ def lambda_handler(event, context): action = event.get("action", "") if path == "/discover" or action == "discover": - # Return agent metadata for Brain server registration + # Return agent metadata for Haxen server registration return self._handle_discovery() - # Auto-register with Brain if needed (for execution requests) - if self.auto_register and not self.brain_connected: + # Auto-register with Haxen if needed (for execution requests) + if self.auto_register and not self.haxen_connected: try: # Attempt registration (non-blocking) - self.brain_handler._register_agent() - self.brain_connected = True + self.haxen_handler._register_agent() + self.haxen_connected = True except Exception as e: if self.dev_mode: log_warn(f"Auto-registration failed: {e}") @@ -661,7 +661,7 @@ def _handle_discovery(self) -> dict: Handle discovery requests for serverless agent registration. Returns agent metadata including reasoners, skills, and configuration - for automatic registration with the Brain server. + for automatic registration with the Haxen server. Returns: dict: Agent metadata for registration @@ -693,10 +693,10 @@ def _initialize_did_system(self): """Initialize DID and VC components.""" try: # Initialize DID Manager - self.did_manager = DIDManager(self.brain_server, self.node_id) + self.did_manager = DIDManager(self.haxen_server, self.node_id) # Initialize VC Generator - self.vc_generator = VCGenerator(self.brain_server) + self.vc_generator = VCGenerator(self.haxen_server) if self.dev_mode: log_debug("DID system initialized") @@ -711,7 +711,7 @@ def _register_memory_event_listeners(self): """Scans for methods decorated with @on_change and registers them as listeners.""" if not self.memory_event_client: self.memory_event_client = MemoryEventClient( - self.brain_server, self._get_current_execution_context() + self.haxen_server, self._get_current_execution_context() ) for name, method in inspect.getmembers(self, predicate=inspect.ismethod): @@ -828,7 +828,7 @@ def get_conversation_summary() -> dict: memory_client = MemoryClient(self.client, self._current_execution_context) if not self.memory_event_client: self.memory_event_client = MemoryEventClient( - self.brain_server, self._get_current_execution_context() + self.haxen_server, self._get_current_execution_context() ) return MemoryInterface(memory_client, self.memory_event_client) @@ -905,7 +905,7 @@ def _build_callback_discovery_payload(self) -> Optional[Dict[str, Any]]: return payload def _apply_discovery_response(self, payload: Optional[Dict[str, Any]]) -> None: - """Update agent networking state from Brain discovery response.""" + """Update agent networking state from Haxen discovery response.""" if not payload: return @@ -925,7 +925,7 @@ def _apply_discovery_response(self, payload: Optional[Dict[str, Any]]) -> None: ) if resolved and resolved != self.base_url: - log_debug(f"Applying resolved callback URL from Brain: {resolved}") + log_debug(f"Applying resolved callback URL from Haxen: {resolved}") self.base_url = resolved if isinstance(discovery_section, dict): @@ -1017,20 +1017,20 @@ def _register_mcp_servers_with_registry(self) -> None: if self.dev_mode: log_debug("MCP server registration disabled - old modules removed") - def _setup_brain_routes(self): + def _setup_haxen_routes(self): """Delegate to server handler for route setup""" - return self.server_handler.setup_brain_routes() + return self.server_handler.setup_haxen_routes() def reasoner(self, path: Optional[str] = None, name: Optional[str] = None): """ Decorator to register a reasoner function. A reasoner is an AI-powered function that takes input and produces structured output using LLMs. - It automatically handles input/output schema generation and integrates with the Brain's AI capabilities. + It automatically handles input/output schema generation and integrates with the Haxen's AI capabilities. Args: path (str, optional): The API endpoint path for this reasoner. Defaults to /reasoners/{function_name}. - name (str, optional): Explicit Brain registration ID. Defaults to the function name. + name (str, optional): Explicit Haxen registration ID. Defaults to the function name. """ def decorator(func: Callable) -> Callable: @@ -1067,7 +1067,7 @@ def decorator(func: Callable) -> Callable: async def endpoint(input_data: InputSchema, request: Request): import asyncio import time - from brain_sdk.execution_context import ( + from haxen_sdk.execution_context import ( set_execution_context, reset_execution_context, ) @@ -1252,7 +1252,7 @@ async def tracked_func(*args, **kwargs): if current_context: # We're in a context managed by the enhanced decorator system # Use the enhanced decorator's tracking mechanism - from brain_sdk.decorators import _execute_with_tracking + from haxen_sdk.decorators import _execute_with_tracking return await _execute_with_tracking(original_func, *args, **kwargs) else: @@ -1390,7 +1390,7 @@ def skill( - Generates input/output schemas from type hints - Creates FastAPI endpoints with proper validation - Integrates with workflow tracking and execution context - - Enables cross-agent communication via the Brain execution gateway + - Enables cross-agent communication via the Haxen execution gateway - Provides access to execution context and memory system Args: @@ -1398,10 +1398,10 @@ def skill( Useful for grouping related functionality (e.g., ["database", "user_management"]). path (str, optional): Custom API endpoint path for this skill. Defaults to "/skills/{function_name}". - name (str, optional): Explicit Brain registration ID. Defaults to the function name. + name (str, optional): Explicit Haxen registration ID. Defaults to the function name. Returns: - Callable: The decorated function with enhanced Brain integration. + Callable: The decorated function with enhanced Haxen integration. Example: ```python @@ -1944,10 +1944,10 @@ async def ai_with_multimodal( # pragma: no cover - relies on external multimoda async def call(self, target: str, *args, **kwargs) -> dict: """ - Initiates a cross-agent call to another reasoner or skill via the Brain execution gateway. + Initiates a cross-agent call to another reasoner or skill via the Haxen execution gateway. This method allows agents to seamlessly communicate and utilize reasoners/skills - deployed on other agent nodes within the Brain ecosystem. It properly propagates + deployed on other agent nodes within the Haxen ecosystem. It properly propagates workflow tracking headers and maintains execution context for DAG building. **Return Type**: Always returns JSON/dict objects, similar to calling any REST API. @@ -2050,8 +2050,8 @@ async def call(self, target: str, *args, **kwargs) -> dict: # 🔧 DEBUG: Validate context before creating child if self.dev_mode: - from brain_sdk.execution_context import get_current_context - from brain_sdk.logger import log_debug + from haxen_sdk.execution_context import get_current_context + from haxen_sdk.logger import log_debug log_debug(f"🔍 CALL_DEBUG: Making cross-agent call to {target}") log_debug(f" Current execution_id: {current_context.execution_id}") @@ -2065,25 +2065,25 @@ async def call(self, target: str, *args, **kwargs) -> dict: # Prepare headers with proper workflow tracking headers = current_context.to_headers() - # DISABLED: Same-agent call detection - Force all calls through Brain server - # This ensures all app.call() requests go through the Brain server for proper + # DISABLED: Same-agent call detection - Force all calls through Haxen server + # This ensures all app.call() requests go through the Haxen server for proper # workflow tracking, execution context, and distributed processing - from brain_sdk.logger import log_debug + from haxen_sdk.logger import log_debug log_debug(f"Cross-agent call to: {target}") - # Check if Brain server is available for cross-agent calls - if not self.brain_connected: - from brain_sdk.logger import log_warn + # Check if Haxen server is available for cross-agent calls + if not self.haxen_connected: + from haxen_sdk.logger import log_warn log_warn( - f"Brain server unavailable - cannot make cross-agent call to {target}" + f"Haxen server unavailable - cannot make cross-agent call to {target}" ) raise Exception( - f"Cross-agent call to {target} failed: Brain server unavailable. Agent is running in local mode." + f"Cross-agent call to {target} failed: Haxen server unavailable. Agent is running in local mode." ) - # Use the enhanced BrainClient to make the call via execution gateway + # Use the enhanced HaxenClient to make the call via execution gateway try: async with self._limit_outbound_calls(): # Check for non-serializable parameters and convert them @@ -2128,7 +2128,7 @@ async def call(self, target: str, *args, **kwargs) -> dict: # Check if async execution is enabled and available use_async_execution = ( - self.async_config.enable_async_execution and self.brain_connected + self.async_config.enable_async_execution and self.haxen_connected ) if use_async_execution: @@ -2237,7 +2237,7 @@ async def _get_async_execution_manager(self) -> AsyncExecutionManager: if self._async_execution_manager is None: # Create async execution manager with the same base URL as the client self._async_execution_manager = AsyncExecutionManager( - base_url=self.brain_server, config=self.async_config + base_url=self.haxen_server, config=self.async_config ) # Start the manager await self._async_execution_manager.start() @@ -2268,18 +2268,18 @@ async def _cleanup_async_resources(self) -> None: try: await self.client.aclose() if self.dev_mode: - log_debug("BrainClient resources closed") + log_debug("HaxenClient resources closed") except Exception as e: if self.dev_mode: - log_debug(f"Error closing BrainClient resources: {e}") + log_debug(f"Error closing HaxenClient resources: {e}") def note(self, message: str, tags: List[str] = None) -> None: """ Add a note to the current execution for debugging and tracking purposes. - This method sends a note to the Brain server asynchronously without blocking + This method sends a note to the Haxen server asynchronously without blocking the current execution. The note is automatically associated with the current - execution context and can be viewed in the Brain UI for debugging and monitoring. + execution context and can be viewed in the Haxen UI for debugging and monitoring. Args: message (str): The note message to log @@ -2336,7 +2336,7 @@ async def _send_note(): ui_api_base = self.client.api_base.replace("/api/v1", "/api/ui/v1") if self.dev_mode: - from brain_sdk.logger import log_debug + from haxen_sdk.logger import log_debug log_debug( f"NOTE DEBUG: Original api_base: {self.client.api_base}" @@ -2355,7 +2355,7 @@ async def _send_note(): headers=headers, ) as response: if self.dev_mode: - from brain_sdk.logger import log_debug + from haxen_sdk.logger import log_debug response_text = await response.text() log_debug( @@ -2381,7 +2381,7 @@ async def _send_note(): ) if self.dev_mode: - from brain_sdk.logger import log_debug + from haxen_sdk.logger import log_debug log_debug( f"NOTE DEBUG (requests): Original api_base: {self.client.api_base}" @@ -2400,7 +2400,7 @@ async def _send_note(): timeout=5.0, ) if self.dev_mode: - from brain_sdk.logger import log_debug + from haxen_sdk.logger import log_debug log_debug( f"NOTE DEBUG (requests): Response status: {response.status_code}" @@ -2418,14 +2418,14 @@ async def _send_note(): ) except Exception as e: if self.dev_mode: - from brain_sdk.logger import log_debug + from haxen_sdk.logger import log_debug log_debug(f"Note request failed: {type(e).__name__}: {e}") except Exception as e: # Silently handle errors to avoid interrupting main workflow if self.dev_mode: - from brain_sdk.logger import log_debug + from haxen_sdk.logger import log_debug log_debug(f"Failed to send note: {type(e).__name__}: {e}") @@ -2462,7 +2462,7 @@ def _get_current_execution_context(self) -> ExecutionContext: ExecutionContext: Current or new execution context """ # Check thread-local context first (most reliable) - from brain_sdk.execution_context import get_current_context + from haxen_sdk.execution_context import get_current_context thread_local_context = get_current_context() @@ -2623,17 +2623,17 @@ def serve( # pragma: no cover - requires full server runtime integration **kwargs, ): """ - Start the agent node server with intelligent port management and Brain integration. + Start the agent node server with intelligent port management and Haxen integration. This method launches the agent as a FastAPI server that can receive reasoner and skill - requests from other agents via the Brain execution gateway. It handles automatic - registration with the Brain server, heartbeat management, and graceful shutdown. + requests from other agents via the Haxen execution gateway. It handles automatic + registration with the Haxen server, heartbeat management, and graceful shutdown. The server provides: - RESTful endpoints for all registered reasoners and skills - Health check endpoints for monitoring - MCP server status and management endpoints - - Automatic Brain server registration and heartbeat + - Automatic Haxen server registration and heartbeat - Graceful shutdown with proper cleanup Args: @@ -2647,7 +2647,7 @@ def serve( # pragma: no cover - requires full server runtime integration - Auto-reload on code changes (if supported) - Detailed error messages - MCP server debugging information - heartbeat_interval (int): The interval in seconds for sending heartbeats to the Brain server. + heartbeat_interval (int): The interval in seconds for sending heartbeats to the Haxen server. Defaults to 2 seconds. Lower values provide faster failure detection but increase network overhead. auto_port (bool): If True, automatically find an available port starting from the @@ -2708,22 +2708,22 @@ def get_status() -> dict: - `GET /docs`: Interactive API documentation (Swagger UI) - `GET /redoc`: Alternative API documentation - Integration with Brain: - - Automatically registers with Brain server on startup + Integration with Haxen: + - Automatically registers with Haxen server on startup - Sends periodic heartbeats to maintain connection - - Receives execution requests via Brain's routing system + - Receives execution requests via Haxen's routing system - Participates in workflow tracking and DAG building - Handles cross-agent communication seamlessly Lifecycle: 1. Server initialization and route setup 2. MCP server startup (if configured) - 3. Brain server registration + 3. Haxen server registration 4. Heartbeat loop starts 5. Ready to receive requests 6. Graceful shutdown on SIGINT/SIGTERM 7. MCP server cleanup - 8. Brain server deregistration + 8. Haxen server deregistration Note: - The server runs indefinitely until interrupted (Ctrl+C) diff --git a/sdk/python/brain_sdk/agent_ai.py b/sdk/python/haxen_sdk/agent_ai.py similarity index 98% rename from sdk/python/brain_sdk/agent_ai.py rename to sdk/python/haxen_sdk/agent_ai.py index 0de16308..92f5ccdb 100644 --- a/sdk/python/brain_sdk/agent_ai.py +++ b/sdk/python/haxen_sdk/agent_ai.py @@ -4,9 +4,9 @@ from typing import Any, Dict, List, Literal, Optional, Type, Union import requests -from brain_sdk.agent_utils import AgentUtils -from brain_sdk.logger import log_debug, log_error, log_warn -from brain_sdk.rate_limiter import StatelessRateLimiter +from haxen_sdk.agent_utils import AgentUtils +from haxen_sdk.logger import log_debug, log_error, log_warn +from haxen_sdk.rate_limiter import StatelessRateLimiter from httpx import HTTPStatusError from pydantic import BaseModel @@ -32,7 +32,7 @@ class OpenAI: class AgentAI: - """AI/LLM Integration functionality for Brain Agent""" + """AI/LLM Integration functionality for Haxen Agent""" def __init__(self, agent_instance): """ @@ -450,7 +450,7 @@ async def _execute_with_fallbacks(): def _process_multimodal_args(self, args: tuple) -> List[Dict[str, Any]]: """Process multimodal arguments into LiteLLM-compatible message format""" - from brain_sdk.multimodal import Audio, File, Image, Text + from haxen_sdk.multimodal import Audio, File, Image, Text messages = [] user_content = [] @@ -824,7 +824,7 @@ async def _generate_tts_audio( Generate audio using LiteLLM's speech function for TTS models. """ import litellm - from brain_sdk.multimodal_response import ( + from haxen_sdk.multimodal_response import ( AudioOutput, MultimodalResponse, ) @@ -909,7 +909,7 @@ async def _generate_openai_direct_audio( import tempfile from pathlib import Path - from brain_sdk.multimodal_response import AudioOutput, MultimodalResponse + from haxen_sdk.multimodal_response import AudioOutput, MultimodalResponse from openai import OpenAI # Combine all text inputs @@ -1059,7 +1059,7 @@ async def ai_with_vision( response = await litellm.aimage_generation(**image_params) # Import multimodal response detection - from brain_sdk.multimodal_response import detect_multimodal_response + from haxen_sdk.multimodal_response import detect_multimodal_response # Detect and wrap multimodal content return detect_multimodal_response(response) diff --git a/sdk/python/brain_sdk/agent_brain.py b/sdk/python/haxen_sdk/agent_haxen.py similarity index 89% rename from sdk/python/brain_sdk/agent_brain.py rename to sdk/python/haxen_sdk/agent_haxen.py index de944d27..e33d348e 100644 --- a/sdk/python/brain_sdk/agent_brain.py +++ b/sdk/python/haxen_sdk/agent_haxen.py @@ -5,8 +5,8 @@ from datetime import datetime import requests -from brain_sdk.types import AgentStatus, HeartbeatData -from brain_sdk.logger import ( +from haxen_sdk.types import AgentStatus, HeartbeatData +from haxen_sdk.logger import ( log_heartbeat, log_debug, log_warn, @@ -17,12 +17,12 @@ ) -class AgentBrain: +class AgentHaxen: """ - Brain Server Communication handler for Agent class. + Haxen Server Communication handler for Agent class. - This class encapsulates all Brain server communication functionality including: - - Agent registration with Brain server + This class encapsulates all Haxen server communication functionality including: + - Agent registration with Haxen server - Heartbeat management (both simple and enhanced) - Fast lifecycle management - Graceful shutdown notifications @@ -31,17 +31,17 @@ class AgentBrain: def __init__(self, agent_instance): """ - Initialize the Brain handler with a reference to the agent instance. + Initialize the Haxen handler with a reference to the agent instance. Args: agent_instance: The Agent instance this handler belongs to """ self.agent = agent_instance - async def register_with_brain_server(self, port: int): - """Register this agent node with Brain server""" + async def register_with_haxen_server(self, port: int): + """Register this agent node with Haxen server""" # Import the callback URL resolution function - from brain_sdk.agent import ( + from haxen_sdk.agent import ( _build_callback_candidates, _resolve_callback_url, _is_running_in_container, @@ -118,7 +118,7 @@ async def register_with_brain_server(self, port: int): try: log_debug( - f"Attempting to register with Brain server at {self.agent.brain_server}" + f"Attempting to register with Haxen server at {self.agent.haxen_server}" ) discovery_payload = self.agent._build_callback_discovery_payload() @@ -132,10 +132,10 @@ async def register_with_brain_server(self, port: int): if success: if payload: self.agent._apply_discovery_response(payload) - log_success(f"Registered node '{self.agent.node_id}' with Brain server") - self.agent.brain_connected = True + log_success(f"Registered node '{self.agent.node_id}' with Haxen server") + self.agent.haxen_connected = True - # Attempt DID registration after successful Brain registration + # Attempt DID registration after successful Haxen registration if self.agent.did_manager: did_success = self.agent._register_agent_with_did() if not did_success and self.agent.dev_mode: @@ -144,18 +144,18 @@ async def register_with_brain_server(self, port: int): ) else: log_error("Registration failed") - self.agent.brain_connected = False + self.agent.haxen_connected = False except Exception as e: - self.agent.brain_connected = False + self.agent.haxen_connected = False if self.agent.dev_mode: - log_warn(f"Brain server not available: {e}") + log_warn(f"Haxen server not available: {e}") log_setup("Running in development mode - agent will work standalone") log_info( - f"To connect to Brain server, start it at {self.agent.brain_server}" + f"To connect to Haxen server, start it at {self.agent.haxen_server}" ) else: - log_error(f"Failed to register with Brain server: {e}") + log_error(f"Failed to register with Haxen server: {e}") if ( isinstance(e, requests.exceptions.RequestException) and e.response is not None @@ -165,13 +165,13 @@ async def register_with_brain_server(self, port: int): raise def send_heartbeat(self): - """Send heartbeat to Brain server""" - if not self.agent.brain_connected: - return # Skip heartbeat if not connected to Brain + """Send heartbeat to Haxen server""" + if not self.agent.haxen_connected: + return # Skip heartbeat if not connected to Haxen try: response = requests.post( - f"{self.agent.brain_server}/api/v1/nodes/{self.agent.node_id}/heartbeat", + f"{self.agent.haxen_server}/api/v1/nodes/{self.agent.node_id}/heartbeat", headers={"Content-Type": "application/json"}, timeout=5, ) @@ -188,8 +188,8 @@ def heartbeat_worker( self, interval: int = 30 ): # pragma: no cover - long-running thread loop """Background worker that sends periodic heartbeats""" - if not self.agent.brain_connected: - log_heartbeat("Heartbeat worker skipped - not connected to Brain server") + if not self.agent.haxen_connected: + log_heartbeat("Heartbeat worker skipped - not connected to Haxen server") return log_heartbeat(f"Starting heartbeat worker (interval: {interval}s)") @@ -199,8 +199,8 @@ def heartbeat_worker( def start_heartbeat(self, interval: int = 30): """Start the heartbeat background thread""" - if not self.agent.brain_connected: - return # Skip heartbeat if not connected to Brain + if not self.agent.haxen_connected: + return # Skip heartbeat if not connected to Haxen if ( self.agent._heartbeat_thread is None @@ -226,7 +226,7 @@ async def send_enhanced_heartbeat(self) -> bool: Returns: True if heartbeat was successful, False otherwise """ - if not self.agent.brain_connected: + if not self.agent.haxen_connected: return False try: @@ -259,12 +259,12 @@ async def send_enhanced_heartbeat(self) -> bool: async def notify_shutdown(self) -> bool: """ - Notify Brain server of graceful shutdown. + Notify Haxen server of graceful shutdown. Returns: True if notification was successful, False otherwise """ - if not self.agent.brain_connected: + if not self.agent.haxen_connected: return False try: @@ -285,12 +285,12 @@ def setup_fast_lifecycle_signal_handlers( """ Setup signal handler for fast lifecycle status while allowing uvicorn to perform graceful shutdown. - - Only intercepts SIGTERM to mark the agent offline and notify Brain immediately. + - Only intercepts SIGTERM to mark the agent offline and notify Haxen immediately. - Leaves SIGINT (Ctrl+C) to uvicorn so its shutdown hooks run and resources are cleaned up. """ def signal_handler(signum: int, frame) -> None: - """Handle SIGTERM: mark offline, notify Brain, then re-emit the signal for default handling.""" + """Handle SIGTERM: mark offline, notify Haxen, then re-emit the signal for default handling.""" signal_name = "SIGTERM" if signum == signal.SIGTERM else "SIGINT" if self.agent.dev_mode: @@ -302,7 +302,7 @@ def signal_handler(signum: int, frame) -> None: self.agent._shutdown_requested = True self.agent._current_status = AgentStatus.OFFLINE - # Best-effort immediate notification to Brain + # Best-effort immediate notification to Haxen try: success = self.agent.client.notify_graceful_shutdown_sync( self.agent.node_id @@ -347,7 +347,7 @@ async def register_with_fast_lifecycle( Returns: True if registration was successful, False otherwise """ - from brain_sdk.agent import _build_callback_candidates, _resolve_callback_url + from haxen_sdk.agent import _build_callback_candidates, _resolve_callback_url if not self.agent.base_url: self.agent.callback_candidates = _build_callback_candidates( @@ -404,7 +404,7 @@ async def register_with_fast_lifecycle( try: if self.agent.dev_mode: log_info( - f"Fast registration with Brain server at {self.agent.brain_server}" + f"Fast registration with Haxen server at {self.agent.haxen_server}" ) log_info(f"Using callback URL: {self.agent.base_url}") @@ -427,9 +427,9 @@ async def register_with_fast_lifecycle( log_success( f"Fast registration successful - Status: {AgentStatus.STARTING.value}" ) - self.agent.brain_connected = True + self.agent.haxen_connected = True - # Attempt DID registration after successful Brain registration + # Attempt DID registration after successful Haxen registration if self.agent.did_manager: did_success = self.agent._register_agent_with_did() if not did_success and self.agent.dev_mode: @@ -441,11 +441,11 @@ async def register_with_fast_lifecycle( else: if self.agent.dev_mode: log_error("Fast registration failed") - self.agent.brain_connected = False + self.agent.haxen_connected = False return False except Exception as e: - self.agent.brain_connected = False + self.agent.haxen_connected = False if self.agent.dev_mode: log_warn(f"Fast registration error: {e}") return False diff --git a/sdk/python/brain_sdk/agent_mcp.py b/sdk/python/haxen_sdk/agent_mcp.py similarity index 96% rename from sdk/python/brain_sdk/agent_mcp.py rename to sdk/python/haxen_sdk/agent_mcp.py index ab1d01e1..d1a9bbf8 100644 --- a/sdk/python/brain_sdk/agent_mcp.py +++ b/sdk/python/haxen_sdk/agent_mcp.py @@ -2,13 +2,13 @@ from datetime import datetime from typing import Any, Dict, List, Optional -from brain_sdk.agent_utils import AgentUtils -from brain_sdk.dynamic_skills import DynamicMCPSkillManager -from brain_sdk.execution_context import ExecutionContext -from brain_sdk.logger import log_debug, log_error, log_info, log_warn -from brain_sdk.mcp_client import MCPClientRegistry -from brain_sdk.mcp_manager import MCPManager -from brain_sdk.types import AgentStatus, MCPServerHealth +from haxen_sdk.agent_utils import AgentUtils +from haxen_sdk.dynamic_skills import DynamicMCPSkillManager +from haxen_sdk.execution_context import ExecutionContext +from haxen_sdk.logger import log_debug, log_error, log_info, log_warn +from haxen_sdk.mcp_client import MCPClientRegistry +from haxen_sdk.mcp_manager import MCPManager +from haxen_sdk.types import AgentStatus, MCPServerHealth from fastapi import Request @@ -292,7 +292,7 @@ async def mcp_skill_function(**kwargs): # Create FastAPI endpoint @self.agent.post(endpoint_path, response_model=dict) async def mcp_skill_endpoint(input_data: InputSchema, request: Request): - from brain_sdk.execution_context import ExecutionContext + from haxen_sdk.execution_context import ExecutionContext # Extract execution context from request headers execution_context = ExecutionContext.from_request( @@ -324,7 +324,7 @@ def _create_and_register_mcp_skill( self, server_alias: str, tool: Dict[str, Any] ) -> None: """ - Create and register a single MCP tool as a Brain skill. + Create and register a single MCP tool as a Haxen skill. Args: server_alias: The alias of the MCP server @@ -372,7 +372,7 @@ async def mcp_skill_function( This is an auto-generated skill that wraps the '{tool_name}' tool from the '{server_alias}' MCP server. Args: - execution_context (ExecutionContext, optional): Brain execution context for workflow tracking + execution_context (ExecutionContext, optional): Haxen execution context for workflow tracking **kwargs: Arguments to pass to the MCP tool Returns: @@ -520,7 +520,7 @@ async def _background_mcp_initialization(self) -> None: self.agent._mcp_initialization_complete = True # Send status update heartbeat - await self.agent.brain_handler.send_enhanced_heartbeat() + await self.agent.haxen_handler.send_enhanced_heartbeat() if self.agent.dev_mode: log_info( @@ -531,4 +531,4 @@ async def _background_mcp_initialization(self) -> None: if self.agent.dev_mode: log_error(f"Background MCP initialization error: {e}") self.agent._current_status = AgentStatus.DEGRADED - await self.agent.brain_handler.send_enhanced_heartbeat() + await self.agent.haxen_handler.send_enhanced_heartbeat() diff --git a/sdk/python/brain_sdk/agent_registry.py b/sdk/python/haxen_sdk/agent_registry.py similarity index 100% rename from sdk/python/brain_sdk/agent_registry.py rename to sdk/python/haxen_sdk/agent_registry.py diff --git a/sdk/python/brain_sdk/agent_server.py b/sdk/python/haxen_sdk/agent_server.py similarity index 95% rename from sdk/python/brain_sdk/agent_server.py rename to sdk/python/haxen_sdk/agent_server.py index 3a87db87..f499eeab 100644 --- a/sdk/python/brain_sdk/agent_server.py +++ b/sdk/python/haxen_sdk/agent_server.py @@ -6,15 +6,15 @@ from typing import Optional import uvicorn -from brain_sdk.agent_utils import AgentUtils -from brain_sdk.logger import log_debug, log_error, log_info, log_success, log_warn -from brain_sdk.utils import get_free_port +from haxen_sdk.agent_utils import AgentUtils +from haxen_sdk.logger import log_debug, log_error, log_info, log_success, log_warn +from haxen_sdk.utils import get_free_port from fastapi import Request from fastapi.routing import APIRoute class AgentServer: - """Server management functionality for Brain Agent""" + """Server management functionality for Haxen Agent""" def __init__(self, agent_instance): """ @@ -25,8 +25,8 @@ def __init__(self, agent_instance): """ self.agent = agent_instance - def setup_brain_routes(self): - """Setup standard routes that Brain server expects""" + def setup_haxen_routes(self): + """Setup standard routes that Haxen server expects""" @self.agent.get("/health") async def health(): @@ -104,7 +104,7 @@ async def shutdown_agent(request: Request): """ Graceful shutdown endpoint for the agent. - This endpoint allows the Brain server to request a graceful shutdown + This endpoint allows the Haxen server to request a graceful shutdown instead of using process signals. """ try: @@ -123,12 +123,12 @@ async def shutdown_agent(request: Request): ) # Set shutdown status - from brain_sdk.agent import AgentStatus + from haxen_sdk.agent import AgentStatus self.agent._shutdown_requested = True self.agent._current_status = AgentStatus.OFFLINE - # Notify Brain server of shutdown initiation + # Notify Haxen server of shutdown initiation try: success = self.agent.client.notify_graceful_shutdown_sync( self.agent.node_id @@ -393,7 +393,7 @@ async def restart_mcp_server(alias: str): @self.agent.get("/health/mcp") async def mcp_health(): - """Get MCP health information in the format expected by Brain server""" + """Get MCP health information in the format expected by Haxen server""" if not self.agent.mcp_manager: # Return empty response when MCP manager is not available return { @@ -499,7 +499,7 @@ async def mcp_health(): @self.agent.post("/mcp/servers/{alias}/restart") async def restart_mcp_server_alt(alias: str): - """Alternative restart endpoint for Brain server compatibility""" + """Alternative restart endpoint for Haxen server compatibility""" return await restart_mcp_server(alias) @self.agent.get("/mcp/servers/{alias}/tools") @@ -562,8 +562,8 @@ async def _graceful_shutdown(self, timeout_seconds: int = 30): # Stop heartbeat try: - if hasattr(self.agent, "brain_handler") and self.agent.brain_handler: - self.agent.brain_handler.stop_heartbeat() + if hasattr(self.agent, "haxen_handler") and self.agent.haxen_handler: + self.agent.haxen_handler.stop_heartbeat() if self.agent.dev_mode: log_debug("Heartbeat stopped") except Exception as e: @@ -572,7 +572,7 @@ async def _graceful_shutdown(self, timeout_seconds: int = 30): # Clear agent registry try: - from brain_sdk.agent_registry import clear_current_agent + from haxen_sdk.agent_registry import clear_current_agent clear_current_agent() except Exception as e: @@ -807,10 +807,10 @@ def serve( """ Start the agent node server with intelligent port management and production-ready configuration. - This method implements smart port resolution that seamlessly works with Brain CLI + This method implements smart port resolution that seamlessly works with Haxen CLI or standalone execution. The port selection priority is: 1. Explicit port parameter (highest priority) - 2. PORT environment variable (Brain CLI integration) + 2. PORT environment variable (Haxen CLI integration) 3. auto_port=True: find free port automatically 4. Default fallback with availability check @@ -819,7 +819,7 @@ def serve( If specified, this takes highest priority. host (str): The host address for the agent server. Defaults to "0.0.0.0". dev (bool): If True, enables development mode features (e.g., hot reload, debug UI). - heartbeat_interval (int): The interval in seconds for sending heartbeats to the Brain server. + heartbeat_interval (int): The interval in seconds for sending heartbeats to the Haxen server. Defaults to 2 seconds (fast detection architecture). auto_port (bool): If True, automatically find an available port. Defaults to False. workers (int, optional): Number of worker processes for production. If None, uses single process. @@ -831,27 +831,27 @@ def serve( """ # Smart port resolution with priority order if port is None: - # Check for Brain CLI integration via environment variable + # Check for Haxen CLI integration via environment variable env_port = os.getenv("PORT") if env_port and env_port.isdigit(): suggested_port = int(env_port) if AgentUtils.is_port_available(suggested_port): port = suggested_port if self.agent.dev_mode: - log_debug(f"Using port from Brain CLI: {port}") + log_debug(f"Using port from Haxen CLI: {port}") else: - # Brain CLI suggested port is taken, find next available + # Haxen CLI suggested port is taken, find next available try: port = get_free_port(start_port=suggested_port) if self.agent.dev_mode: log_debug( - f"Brain CLI port {suggested_port} taken, using {port}" + f"Haxen CLI port {suggested_port} taken, using {port}" ) except RuntimeError: port = get_free_port() # Fallback to default range if self.agent.dev_mode: log_debug(f"Using fallback port: {port}") - elif auto_port or os.getenv("BRAIN_AUTO_PORT") == "true": + elif auto_port or os.getenv("HAXEN_AUTO_PORT") == "true": # Auto-port mode: find any available port try: port = get_free_port() @@ -908,7 +908,7 @@ def serve( log_debug(f"Using explicit callback URL: {self.agent.base_url}") # Start heartbeat worker - self.agent.brain_handler.start_heartbeat(heartbeat_interval) + self.agent.haxen_handler.start_heartbeat(heartbeat_interval) log_info(f"Agent server running at http://{host}:{port}") log_info("Available endpoints:") @@ -920,19 +920,19 @@ def serve( log_debug(f"Endpoint registered: {method} {route.path}") # Setup fast lifecycle signal handlers - self.agent.brain_handler.setup_fast_lifecycle_signal_handlers() + self.agent.haxen_handler.setup_fast_lifecycle_signal_handlers() # Add startup event handler for resilient lifecycle @self.agent.on_event("startup") async def startup_resilient_lifecycle(): - """Resilient lifecycle startup: connection manager handles Brain server connectivity""" + """Resilient lifecycle startup: connection manager handles Haxen server connectivity""" # Initialize connection manager - from brain_sdk.connection_manager import ConnectionConfig, ConnectionManager + from haxen_sdk.connection_manager import ConnectionConfig, ConnectionManager # Configure connection manager with reasonable retry interval config = ConnectionConfig( - retry_interval=10.0, # Check every 10 seconds for Brain server + retry_interval=10.0, # Check every 10 seconds for Haxen server health_check_interval=30.0, connection_timeout=10.0, ) @@ -942,11 +942,11 @@ async def startup_resilient_lifecycle(): # Set up callbacks for connection state changes def on_connected(): if self.agent.dev_mode: - log_info("Connected to Brain server - full functionality available") + log_info("Connected to Haxen server - full functionality available") # Kick a heartbeat immediately so the control plane renews the lease try: asyncio.create_task( - self.agent.brain_handler.send_enhanced_heartbeat() + self.agent.haxen_handler.send_enhanced_heartbeat() ) except RuntimeError: # Event loop not running; the heartbeat worker will recover shortly @@ -957,14 +957,14 @@ def on_connected(): or self.agent._heartbeat_task.done() ): self.agent._heartbeat_task = asyncio.create_task( - self.agent.brain_handler.enhanced_heartbeat_loop( + self.agent.haxen_handler.enhanced_heartbeat_loop( heartbeat_interval ) ) def on_disconnected(): if self.agent.dev_mode: - log_warn("Brain server disconnected - running in local mode") + log_warn("Haxen server disconnected - running in local mode") # Cancel heartbeat task when disconnected if ( hasattr(self.agent, "_heartbeat_task") @@ -979,7 +979,7 @@ def on_disconnected(): connected = await self.agent.connection_manager.start() # Always connect memory event client and start MCP initialization - # These work independently of Brain server connection + # These work independently of Haxen server connection if self.agent.memory_event_client: try: await self.agent.memory_event_client.connect() @@ -992,11 +992,11 @@ def on_disconnected(): if connected: if self.agent.dev_mode: - log_info("Agent started with Brain server connection") + log_info("Agent started with Haxen server connection") else: if self.agent.dev_mode: log_info( - "Agent started in local mode - will connect to Brain server when available" + "Agent started in local mode - will connect to Haxen server when available" ) # Add shutdown event handler for cleanup @@ -1034,10 +1034,10 @@ async def shutdown_cleanup(): await self.agent.client.aclose() except Exception as e: if self.agent.dev_mode: - log_error(f"Brain client shutdown error: {e}") + log_error(f"Haxen client shutdown error: {e}") # Clear agent from thread-local storage during shutdown - from brain_sdk.agent_registry import clear_current_agent + from haxen_sdk.agent_registry import clear_current_agent clear_current_agent() @@ -1147,7 +1147,7 @@ async def shutdown_cleanup(): log_info("Agent shutdown initiated...") # Stop heartbeat worker - self.agent.brain_handler.stop_heartbeat() + self.agent.haxen_handler.stop_heartbeat() # Stop all MCP servers self.agent.mcp_handler._cleanup_mcp_servers() diff --git a/sdk/python/brain_sdk/agent_utils.py b/sdk/python/haxen_sdk/agent_utils.py similarity index 100% rename from sdk/python/brain_sdk/agent_utils.py rename to sdk/python/haxen_sdk/agent_utils.py diff --git a/sdk/python/brain_sdk/agent_workflow.py b/sdk/python/haxen_sdk/agent_workflow.py similarity index 97% rename from sdk/python/brain_sdk/agent_workflow.py rename to sdk/python/haxen_sdk/agent_workflow.py index a90824f3..606c915d 100644 --- a/sdk/python/brain_sdk/agent_workflow.py +++ b/sdk/python/haxen_sdk/agent_workflow.py @@ -2,7 +2,7 @@ import time from typing import Any, Callable, Dict, Optional -from brain_sdk.logger import log_debug, log_warn +from haxen_sdk.logger import log_debug, log_warn from .execution_context import ( ExecutionContext, @@ -13,7 +13,7 @@ class AgentWorkflow: - """Workflow helper that keeps local execution metadata in sync with Brain.""" + """Workflow helper that keeps local execution metadata in sync with Haxen.""" def __init__(self, agent_instance): self.agent = agent_instance @@ -174,10 +174,10 @@ async def notify_call_error( await self.fire_and_forget_update(payload) async def fire_and_forget_update(self, payload: Dict[str, Any]) -> None: - """Send workflow update to Brain when a client is available.""" + """Send workflow update to Haxen when a client is available.""" client = getattr(self.agent, "client", None) - base_url = getattr(self.agent, "brain_server", None) + base_url = getattr(self.agent, "haxen_server", None) if not client or not hasattr(client, "_async_request") or not base_url: return @@ -224,7 +224,7 @@ async def _ensure_execution_registered( return context client = getattr(self.agent, "client", None) - base_url = getattr(self.agent, "brain_server", None) + base_url = getattr(self.agent, "haxen_server", None) if not client or not hasattr(client, "_async_request") or not base_url: context.registered = True return context diff --git a/sdk/python/brain_sdk/async_config.py b/sdk/python/haxen_sdk/async_config.py similarity index 97% rename from sdk/python/brain_sdk/async_config.py rename to sdk/python/haxen_sdk/async_config.py index 44d252a5..401e3e0b 100644 --- a/sdk/python/brain_sdk/async_config.py +++ b/sdk/python/haxen_sdk/async_config.py @@ -1,5 +1,5 @@ """ -Async execution configuration for the Brain SDK. +Async execution configuration for the Haxen SDK. This module provides configuration classes for managing async execution behavior, polling strategies, resource limits, and performance tuning parameters. @@ -91,10 +91,10 @@ def from_environment(cls) -> "AsyncConfig": """ Create AsyncConfig from environment variables. - Environment variables use the prefix BRAIN_ASYNC_ followed by the + Environment variables use the prefix HAXEN_ASYNC_ followed by the uppercase parameter name. For example: - - BRAIN_ASYNC_MAX_EXECUTION_TIMEOUT=1800 - - BRAIN_ASYNC_BATCH_SIZE=50 + - HAXEN_ASYNC_MAX_EXECUTION_TIMEOUT=1800 + - HAXEN_ASYNC_BATCH_SIZE=50 Returns: AsyncConfig instance with values from environment variables @@ -103,7 +103,7 @@ def from_environment(cls) -> "AsyncConfig": # Helper function to get env var with type conversion def get_env_var(name: str, default_value, converter=None): - env_name = f"BRAIN_ASYNC_{name.upper()}" + env_name = f"HAXEN_ASYNC_{name.upper()}" value = os.getenv(env_name) if value is None: return default_value diff --git a/sdk/python/brain_sdk/async_execution_manager.py b/sdk/python/haxen_sdk/async_execution_manager.py similarity index 99% rename from sdk/python/brain_sdk/async_execution_manager.py rename to sdk/python/haxen_sdk/async_execution_manager.py index f66517c7..3e6ede3a 100644 --- a/sdk/python/brain_sdk/async_execution_manager.py +++ b/sdk/python/haxen_sdk/async_execution_manager.py @@ -1,5 +1,5 @@ """ -Async Execution Manager for the Brain SDK. +Async Execution Manager for the Haxen SDK. This module provides the central orchestrator for managing hundreds of concurrent async executions with intelligent polling, resource management, and comprehensive @@ -139,7 +139,7 @@ def __init__( Initialize the async execution manager. Args: - base_url: Base URL for the brain server + base_url: Base URL for the haxen server config: AsyncConfig instance for configuration parameters connection_manager: Optional ConnectionManager instance result_cache: Optional ResultCache instance diff --git a/sdk/python/brain_sdk/client.py b/sdk/python/haxen_sdk/client.py similarity index 99% rename from sdk/python/brain_sdk/client.py rename to sdk/python/haxen_sdk/client.py index 0e536970..190f1f18 100644 --- a/sdk/python/brain_sdk/client.py +++ b/sdk/python/haxen_sdk/client.py @@ -65,7 +65,7 @@ class _Submission: target_type: Optional[str] = None -class BrainClient: +class HaxenClient: def __init__( self, base_url: str = "http://localhost:8080", @@ -179,7 +179,7 @@ async def get_async_http_client(self) -> "httpx.AsyncClient": client_kwargs = { "headers": { - "User-Agent": "BrainSDK/1.0", + "User-Agent": "HaxenSDK/1.0", "Accept": "application/json", } } @@ -254,7 +254,7 @@ def _sync_request(method: str, url: str, **kwargs): # Add User-Agent if not present if "User-Agent" not in kwargs["headers"]: - kwargs["headers"]["User-Agent"] = "BrainSDK/1.0" + kwargs["headers"]["User-Agent"] = "HaxenSDK/1.0" # DIAGNOSTIC: Log request details logger.debug(f"🔍 SYNC_REQUEST: Headers: {kwargs.get('headers', {})}") @@ -305,7 +305,7 @@ async def aclose(self) -> None: self._async_http_client_lock = None def register_node(self, node_data: Dict[str, Any]) -> Dict[str, Any]: - """Register agent node with Brain server""" + """Register agent node with Haxen server""" response = requests.post(f"{self.api_base}/nodes/register", json=node_data) response.raise_for_status() # Raise an exception for bad status codes return response.json() @@ -334,7 +334,7 @@ async def register_agent( base_url: str, discovery: Optional[Dict[str, Any]] = None, ) -> Tuple[bool, Optional[Dict[str, Any]]]: - """Register or update agent information with Brain server.""" + """Register or update agent information with Haxen server.""" try: registration_data = { "id": node_id, @@ -709,7 +709,7 @@ async def send_enhanced_heartbeat( self, node_id: str, heartbeat_data: HeartbeatData ) -> bool: """ - Send enhanced heartbeat with status and MCP information to Brain server. + Send enhanced heartbeat with status and MCP information to Haxen server. Args: node_id: The agent node ID @@ -758,7 +758,7 @@ def send_enhanced_heartbeat_sync( async def notify_graceful_shutdown(self, node_id: str) -> bool: """ - Notify Brain server that the agent is shutting down gracefully. + Notify Haxen server that the agent is shutting down gracefully. Args: node_id: The agent node ID @@ -1246,7 +1246,7 @@ async def close_async_execution_manager(self) -> None: """ Close the async execution manager and cleanup resources. - This should be called when the BrainClient is no longer needed + This should be called when the HaxenClient is no longer needed to ensure proper cleanup of background tasks and connections. """ if self._async_execution_manager is not None: diff --git a/sdk/python/brain_sdk/connection_manager.py b/sdk/python/haxen_sdk/connection_manager.py similarity index 91% rename from sdk/python/brain_sdk/connection_manager.py rename to sdk/python/haxen_sdk/connection_manager.py index 66dd1195..9f14d180 100644 --- a/sdk/python/brain_sdk/connection_manager.py +++ b/sdk/python/haxen_sdk/connection_manager.py @@ -1,7 +1,7 @@ """ -Brain SDK Connection Manager +Haxen SDK Connection Manager -Provides resilient connection handling for Brain server connectivity. +Provides resilient connection handling for Haxen server connectivity. Handles automatic reconnection, graceful degradation, and connection health monitoring. """ @@ -10,17 +10,17 @@ from enum import Enum from typing import Optional, Callable, Any, Dict from dataclasses import dataclass -from brain_sdk.logger import log_debug, log_info, log_warn, log_error +from haxen_sdk.logger import log_debug, log_info, log_warn, log_error class ConnectionState(Enum): - """Connection states for Brain server connectivity""" + """Connection states for Haxen server connectivity""" DISCONNECTED = "disconnected" CONNECTING = "connecting" CONNECTED = "connected" RECONNECTING = "reconnecting" - DEGRADED = "degraded" # Running locally without Brain server + DEGRADED = "degraded" # Running locally without Haxen server @dataclass @@ -34,11 +34,11 @@ class ConnectionConfig: class ConnectionManager: """ - Manages resilient connections to Brain server with automatic reconnection, + Manages resilient connections to Haxen server with automatic reconnection, graceful degradation, and health monitoring. Uses a simple, consistent retry interval to ensure immediate reconnection - when Brain server becomes available. + when Haxen server becomes available. """ def __init__(self, agent, config: Optional[ConnectionConfig] = None): @@ -104,16 +104,16 @@ async def stop(self): async def _attempt_connection(self) -> bool: """ - Attempt to connect to Brain server. + Attempt to connect to Haxen server. Returns: True if connection successful, False otherwise """ try: self.state = ConnectionState.CONNECTING - log_debug("Attempting connection to Brain server") + log_debug("Attempting connection to Haxen server") - # Try to register with Brain server - suppress verbose error logging + # Try to register with Haxen server - suppress verbose error logging import logging # Temporarily suppress httpx and httpcore logging to avoid verbose connection errors @@ -171,7 +171,7 @@ async def _health_check_loop(self): break # Try to send a heartbeat to check connection health - success = await self.agent.brain_handler.send_enhanced_heartbeat() + success = await self.agent.haxen_handler.send_enhanced_heartbeat() if not success: log_warn("Health check failed - connection lost") @@ -227,9 +227,9 @@ def _on_connection_success(self): """Handle successful connection""" self.state = ConnectionState.CONNECTED self.last_successful_connection = time.time() - self.agent.brain_connected = True + self.agent.haxen_connected = True - log_info("Connected to Brain server") + log_info("Connected to Haxen server") if self.on_connected: try: @@ -240,9 +240,9 @@ def _on_connection_success(self): def _on_connection_failure(self): """Handle connection failure""" self.state = ConnectionState.DEGRADED - self.agent.brain_connected = False + self.agent.haxen_connected = False - log_warn("Brain server unavailable - running in degraded mode") + log_warn("Haxen server unavailable - running in degraded mode") if self.on_disconnected: try: @@ -251,7 +251,7 @@ def _on_connection_failure(self): log_error(f"Error in disconnection callback: {e}") def is_connected(self) -> bool: - """Check if currently connected to Brain server""" + """Check if currently connected to Haxen server""" return self.state == ConnectionState.CONNECTED def is_degraded(self) -> bool: diff --git a/sdk/python/brain_sdk/decorators.py b/sdk/python/haxen_sdk/decorators.py similarity index 99% rename from sdk/python/brain_sdk/decorators.py rename to sdk/python/haxen_sdk/decorators.py index 503c6541..175ce9bd 100644 --- a/sdk/python/brain_sdk/decorators.py +++ b/sdk/python/haxen_sdk/decorators.py @@ -1,5 +1,5 @@ """ -Enhanced decorators for Brain SDK with automatic workflow tracking. +Enhanced decorators for Haxen SDK with automatic workflow tracking. Provides always-on workflow tracking for reasoner calls. """ @@ -9,7 +9,7 @@ import time from typing import Any, Callable, Dict, List, Optional, Union -from brain_sdk.logger import log_warn +from haxen_sdk.logger import log_warn from .execution_context import ( ExecutionContext, diff --git a/sdk/python/brain_sdk/did_manager.py b/sdk/python/haxen_sdk/did_manager.py similarity index 93% rename from sdk/python/brain_sdk/did_manager.py rename to sdk/python/haxen_sdk/did_manager.py index b3a5532f..89bf3191 100644 --- a/sdk/python/brain_sdk/did_manager.py +++ b/sdk/python/haxen_sdk/did_manager.py @@ -1,5 +1,5 @@ """ -DID Manager for Brain SDK +DID Manager for Haxen SDK Handles Decentralized Identity (DID) and Verifiable Credentials (VC) functionality for agent nodes, reasoners, and skills. @@ -34,7 +34,7 @@ class DIDIdentityPackage: agent_did: DIDIdentity reasoner_dids: Dict[str, DIDIdentity] skill_dids: Dict[str, DIDIdentity] - brain_server_id: str + haxen_server_id: str @dataclass @@ -52,24 +52,24 @@ class DIDExecutionContext: class DIDManager: """ - Manages DID operations for Brain SDK agents. + Manages DID operations for Haxen SDK agents. Handles: - - Agent registration with Brain Server + - Agent registration with Haxen Server - DID resolution and verification - Execution context creation - Integration with agent lifecycle """ - def __init__(self, brain_server_url: str, agent_node_id: str): + def __init__(self, haxen_server_url: str, agent_node_id: str): """ Initialize DID Manager. Args: - brain_server_url: URL of the Brain Server + haxen_server_url: URL of the Haxen Server agent_node_id: Unique identifier for this agent node """ - self.brain_server_url = brain_server_url.rstrip("/") + self.haxen_server_url = haxen_server_url.rstrip("/") self.agent_node_id = agent_node_id self.identity_package: Optional[DIDIdentityPackage] = None self.enabled = False @@ -78,7 +78,7 @@ def register_agent( self, reasoners: List[Dict[str, Any]], skills: List[Dict[str, Any]] ) -> bool: """ - Register agent with Brain Server and obtain DID identity package. + Register agent with Haxen Server and obtain DID identity package. Args: reasoners: List of reasoner definitions @@ -100,9 +100,9 @@ def register_agent( "skills": skills, } - # Send registration request to Brain Server + # Send registration request to Haxen Server response = requests.post( - f"{self.brain_server_url}/api/v1/did/register", + f"{self.haxen_server_url}/api/v1/did/register", json=registration_data, timeout=30, ) @@ -216,7 +216,7 @@ def resolve_did(self, did: str) -> Optional[Dict[str, Any]]: """ try: response = requests.get( - f"{self.brain_server_url}/api/v1/did/resolve/{did}", timeout=10 + f"{self.haxen_server_url}/api/v1/did/resolve/{did}", timeout=10 ) if response.status_code == 200: @@ -246,7 +246,7 @@ def get_identity_summary(self) -> Dict[str, Any]: return { "enabled": True, "agent_did": self.identity_package.agent_did.did, - "brain_server_id": self.identity_package.brain_server_id, + "haxen_server_id": self.identity_package.haxen_server_id, "reasoner_count": len(self.identity_package.reasoner_dids), "skill_count": len(self.identity_package.skill_dids), "reasoner_dids": { @@ -302,7 +302,7 @@ def _parse_identity_package( agent_did=agent_did, reasoner_dids=reasoner_dids, skill_dids=skill_dids, - brain_server_id=package_data["brain_server_id"], + haxen_server_id=package_data["haxen_server_id"], ) def _get_function_did(self, function_name: str) -> Optional[str]: diff --git a/sdk/python/brain_sdk/dynamic_skills.py b/sdk/python/haxen_sdk/dynamic_skills.py similarity index 95% rename from sdk/python/brain_sdk/dynamic_skills.py rename to sdk/python/haxen_sdk/dynamic_skills.py index 5cb6e857..134d2e2b 100644 --- a/sdk/python/brain_sdk/dynamic_skills.py +++ b/sdk/python/haxen_sdk/dynamic_skills.py @@ -4,17 +4,17 @@ from pydantic import BaseModel, create_model from fastapi import Request -from brain_sdk.agent_utils import AgentUtils -from brain_sdk.execution_context import ExecutionContext -from brain_sdk.logger import log_debug, log_error, log_info, log_warn +from haxen_sdk.agent_utils import AgentUtils +from haxen_sdk.execution_context import ExecutionContext +from haxen_sdk.logger import log_debug, log_error, log_info, log_warn class DynamicMCPSkillManager: """ - Dynamic MCP Skill Generator that converts MCP tools into Brain skills. + Dynamic MCP Skill Generator that converts MCP tools into Haxen skills. This class discovers MCP servers, lists their tools, and dynamically - registers each tool as a Brain skill with proper schema generation + registers each tool as a Haxen skill with proper schema generation and execution context handling. """ @@ -23,7 +23,7 @@ def __init__(self, agent, dev_mode: bool = False): Initialize the Dynamic MCP Skill Manager. Args: - agent: The Brain agent instance + agent: The Haxen agent instance dev_mode: Enable development mode logging """ self.agent = agent @@ -32,7 +32,7 @@ def __init__(self, agent, dev_mode: bool = False): async def discover_and_register_all_skills(self) -> None: """ - Discover and register all MCP tools as Brain skills. + Discover and register all MCP tools as Haxen skills. This method: 1. Checks for MCP client registry availability @@ -40,7 +40,7 @@ async def discover_and_register_all_skills(self) -> None: 3. Waits for server readiness 4. Performs health checks on each server 5. Lists tools from healthy servers - 6. Registers each tool as a Brain skill + 6. Registers each tool as a Haxen skill """ if not self.agent.mcp_client_registry: if self.dev_mode: @@ -119,7 +119,7 @@ async def _register_mcp_tool_as_skill( self, server_alias: str, tool: Dict[str, Any], skill_name: str ) -> None: """ - Register an MCP tool as a Brain skill. + Register an MCP tool as a Haxen skill. This method: 1. Extracts tool metadata (name, description) diff --git a/sdk/python/brain_sdk/execution_context.py b/sdk/python/haxen_sdk/execution_context.py similarity index 98% rename from sdk/python/brain_sdk/execution_context.py rename to sdk/python/haxen_sdk/execution_context.py index cbe02f74..d739a9d2 100644 --- a/sdk/python/brain_sdk/execution_context.py +++ b/sdk/python/haxen_sdk/execution_context.py @@ -55,7 +55,7 @@ def to_headers(self) -> Dict[str, str]: Produce the headers that should be forwarded for downstream executions. We only send the run identifier and the current execution as the parent. - The Brain backend issues fresh execution IDs for child nodes. + The Haxen backend issues fresh execution IDs for child nodes. """ parent_execution = self.parent_execution_id or self.execution_id @@ -90,7 +90,7 @@ def child_context(self) -> "ExecutionContext": Create an in-process child context for local tracking. The new execution ID is generated locally so callers can reference - it while awaiting downstream responses. The Brain server will still + it while awaiting downstream responses. The Haxen server will still assign its own execution ID when the child request is submitted. """ diff --git a/sdk/python/brain_sdk/execution_state.py b/sdk/python/haxen_sdk/execution_state.py similarity index 100% rename from sdk/python/brain_sdk/execution_state.py rename to sdk/python/haxen_sdk/execution_state.py diff --git a/sdk/python/brain_sdk/http_connection_manager.py b/sdk/python/haxen_sdk/http_connection_manager.py similarity index 99% rename from sdk/python/brain_sdk/http_connection_manager.py rename to sdk/python/haxen_sdk/http_connection_manager.py index 380b2e00..8bd25763 100644 --- a/sdk/python/brain_sdk/http_connection_manager.py +++ b/sdk/python/haxen_sdk/http_connection_manager.py @@ -3,7 +3,7 @@ This module provides aiohttp session pooling with configurable connection limits, connection reuse, proper cleanup, timeout handling, and connection health monitoring. -Supports both single requests and batch operations for the Brain SDK async execution. +Supports both single requests and batch operations for the Haxen SDK async execution. """ import asyncio @@ -161,7 +161,7 @@ async def start(self) -> None: connector=self._connector, timeout=timeout, headers={ - "User-Agent": "Brain-SDK-AsyncClient/1.0", + "User-Agent": "Haxen-SDK-AsyncClient/1.0", "Accept": "application/json", "Content-Type": "application/json", }, diff --git a/sdk/python/brain_sdk/logger.py b/sdk/python/haxen_sdk/logger.py similarity index 89% rename from sdk/python/brain_sdk/logger.py rename to sdk/python/haxen_sdk/logger.py index 9bdbd65c..f53a8096 100644 --- a/sdk/python/brain_sdk/logger.py +++ b/sdk/python/haxen_sdk/logger.py @@ -1,7 +1,7 @@ """ -Brain SDK Logging Utility +Haxen SDK Logging Utility -This module provides a centralized logging system for the Brain SDK that: +This module provides a centralized logging system for the Haxen SDK that: - Replaces print statements with proper logging - Provides configurable log levels - Truncates long messages and payloads @@ -17,7 +17,7 @@ class LogLevel(Enum): - """Log levels for Brain SDK""" + """Log levels for Haxen SDK""" DEBUG = "DEBUG" INFO = "INFO" @@ -26,23 +26,23 @@ class LogLevel(Enum): ERROR = "ERROR" -class BrainLogger: +class HaxenLogger: """ - Centralized logger for Brain SDK with configurable verbosity and payload truncation. + Centralized logger for Haxen SDK with configurable verbosity and payload truncation. Supports runtime log level changes (e.g., for dev_mode). """ - def __init__(self, name: str = "brain_sdk"): + def __init__(self, name: str = "haxen_sdk"): self.logger = logging.getLogger(name) self._setup_logger() # Configuration from environment variables - default to WARNING (only important events) - self.log_level = os.getenv("BRAIN_LOG_LEVEL", "WARNING").upper() - self.truncate_length = int(os.getenv("BRAIN_LOG_TRUNCATE", "200")) - self.show_payloads = os.getenv("BRAIN_LOG_PAYLOADS", "false").lower() == "true" - self.show_tracking = os.getenv("BRAIN_LOG_TRACKING", "false").lower() == "true" - self.show_fire = os.getenv("BRAIN_LOG_FIRE", "false").lower() == "true" + self.log_level = os.getenv("HAXEN_LOG_LEVEL", "WARNING").upper() + self.truncate_length = int(os.getenv("HAXEN_LOG_TRUNCATE", "200")) + self.show_payloads = os.getenv("HAXEN_LOG_PAYLOADS", "false").lower() == "true" + self.show_tracking = os.getenv("HAXEN_LOG_TRACKING", "false").lower() == "true" + self.show_fire = os.getenv("HAXEN_LOG_FIRE", "false").lower() == "true" # Set logger level based on configuration level_map = { @@ -84,7 +84,7 @@ def _truncate_message(self, message: str) -> str: def _format_payload(self, payload: Any) -> str: """Format payload for logging with truncation""" if not self.show_payloads: - return "[payload hidden - set BRAIN_LOG_PAYLOADS=true to show]" + return "[payload hidden - set HAXEN_LOG_PAYLOADS=true to show]" try: if isinstance(payload, dict): @@ -101,12 +101,12 @@ def heartbeat(self, message: str, **kwargs): self.logger.debug(f"💓 {message}") def track(self, message: str, **kwargs): - """Log tracking messages (controlled by BRAIN_LOG_TRACKING)""" + """Log tracking messages (controlled by HAXEN_LOG_TRACKING)""" if self.show_tracking: self.logger.debug(f"🔍 TRACK: {self._truncate_message(message)}") def fire(self, message: str, payload: Optional[Any] = None, **kwargs): - """Log fire-and-forget workflow messages (controlled by BRAIN_LOG_FIRE)""" + """Log fire-and-forget workflow messages (controlled by HAXEN_LOG_FIRE)""" if self.show_fire: if payload is not None: formatted_payload = self._format_payload(payload) @@ -171,11 +171,11 @@ def security(self, message: str, **kwargs): _global_logger = None -def get_logger(name: str = "brain_sdk") -> BrainLogger: - """Get or create a Brain SDK logger instance""" +def get_logger(name: str = "haxen_sdk") -> HaxenLogger: + """Get or create a Haxen SDK logger instance""" global _global_logger if _global_logger is None: - _global_logger = BrainLogger(name) + _global_logger = HaxenLogger(name) return _global_logger diff --git a/sdk/python/brain_sdk/mcp_client.py b/sdk/python/haxen_sdk/mcp_client.py similarity index 99% rename from sdk/python/brain_sdk/mcp_client.py rename to sdk/python/haxen_sdk/mcp_client.py index d24126e4..fcf18f7e 100644 --- a/sdk/python/brain_sdk/mcp_client.py +++ b/sdk/python/haxen_sdk/mcp_client.py @@ -3,7 +3,7 @@ import aiohttp from aiohttp import ClientTimeout -from brain_sdk.logger import log_debug, log_error, log_info, log_warn +from haxen_sdk.logger import log_debug, log_error, log_info, log_warn class MCPClient: diff --git a/sdk/python/brain_sdk/mcp_manager.py b/sdk/python/haxen_sdk/mcp_manager.py similarity index 100% rename from sdk/python/brain_sdk/mcp_manager.py rename to sdk/python/haxen_sdk/mcp_manager.py diff --git a/sdk/python/brain_sdk/mcp_stdio_bridge.py b/sdk/python/haxen_sdk/mcp_stdio_bridge.py similarity index 99% rename from sdk/python/brain_sdk/mcp_stdio_bridge.py rename to sdk/python/haxen_sdk/mcp_stdio_bridge.py index c899a686..a3373bab 100644 --- a/sdk/python/brain_sdk/mcp_stdio_bridge.py +++ b/sdk/python/haxen_sdk/mcp_stdio_bridge.py @@ -259,7 +259,7 @@ async def _initialize_mcp_session(self) -> bool: init_params = { "protocolVersion": "2024-11-05", "capabilities": {"roots": {"listChanged": True}}, - "clientInfo": {"name": "brain-stdio-bridge", "version": "1.0.0"}, + "clientInfo": {"name": "haxen-stdio-bridge", "version": "1.0.0"}, } response = await self._send_stdio_request("initialize", init_params) diff --git a/sdk/python/brain_sdk/memory.py b/sdk/python/haxen_sdk/memory.py similarity index 94% rename from sdk/python/brain_sdk/memory.py rename to sdk/python/haxen_sdk/memory.py index 7b480571..c52ea7df 100644 --- a/sdk/python/brain_sdk/memory.py +++ b/sdk/python/haxen_sdk/memory.py @@ -1,5 +1,5 @@ """ -Cross-Agent Persistent Memory Client for Brain SDK. +Cross-Agent Persistent Memory Client for Haxen SDK. This module provides the memory interface that enables seamless, automatic memory sharing and synchronization across distributed agents. @@ -8,27 +8,27 @@ import asyncio import json from typing import Any, List, Optional, Union -from .client import BrainClient +from .client import HaxenClient from .execution_context import ExecutionContext from .memory_events import MemoryEventClient, ScopedMemoryEventClient class MemoryClient: """ - Core memory client that communicates with the Brain server's memory API. + Core memory client that communicates with the Haxen server's memory API. This client handles the low-level HTTP operations for memory management and automatically includes execution context headers for proper scoping. """ - def __init__(self, brain_client: BrainClient, execution_context: ExecutionContext): - self.brain_client = brain_client + def __init__(self, haxen_client: HaxenClient, execution_context: ExecutionContext): + self.haxen_client = haxen_client self.execution_context = execution_context async def _async_request(self, method: str, url: str, **kwargs): """Internal helper to perform HTTP requests with graceful fallbacks.""" - if hasattr(self.brain_client, "_async_request"): - return await self.brain_client._async_request(method, url, **kwargs) + if hasattr(self.haxen_client, "_async_request"): + return await self.haxen_client._async_request(method, url, **kwargs) try: import httpx @@ -49,7 +49,7 @@ async def set(self, key: str, data: Any, scope: Optional[str] = None) -> None: data: The data to store (will be JSON serialized) scope: Optional explicit scope override """ - from brain_sdk.logger import log_debug + from haxen_sdk.logger import log_debug headers = self.execution_context.to_headers() @@ -68,12 +68,12 @@ async def set(self, key: str, data: Any, scope: Optional[str] = None) -> None: ) raise - # Use synchronous requests to avoid event loop conflicts with Brain SDK - url = f"{self.brain_client.api_base}/memory/set" + # Use synchronous requests to avoid event loop conflicts with Haxen SDK + url = f"{self.haxen_client.api_base}/memory/set" try: - if hasattr(self.brain_client, "_async_request"): - response = await self.brain_client._async_request( + if hasattr(self.haxen_client, "_async_request"): + response = await self.haxen_client._async_request( "POST", url, json=payload, @@ -119,7 +119,7 @@ async def get( response = await self._async_request( "POST", - f"{self.brain_client.api_base}/memory/get", + f"{self.haxen_client.api_base}/memory/get", json=payload, headers=headers, timeout=10.0, @@ -178,7 +178,7 @@ async def delete(self, key: str, scope: Optional[str] = None) -> None: response = await self._async_request( "DELETE", - f"{self.brain_client.api_base}/memory/delete", + f"{self.haxen_client.api_base}/memory/delete", json=payload, headers=headers, timeout=10.0, @@ -199,7 +199,7 @@ async def list_keys(self, scope: str) -> List[str]: response = await self._async_request( "GET", - f"{self.brain_client.api_base}/memory/list", + f"{self.haxen_client.api_base}/memory/list", params={"scope": scope}, headers=headers, timeout=10.0, diff --git a/sdk/python/brain_sdk/memory_events.py b/sdk/python/haxen_sdk/memory_events.py similarity index 99% rename from sdk/python/brain_sdk/memory_events.py rename to sdk/python/haxen_sdk/memory_events.py index ddc8f3b8..fa2ad63b 100644 --- a/sdk/python/brain_sdk/memory_events.py +++ b/sdk/python/haxen_sdk/memory_events.py @@ -7,7 +7,7 @@ import websockets -from brain_sdk.logger import log_error, log_info +from haxen_sdk.logger import log_error, log_info from .types import MemoryChangeEvent diff --git a/sdk/python/brain_sdk/multimodal.py b/sdk/python/haxen_sdk/multimodal.py similarity index 100% rename from sdk/python/brain_sdk/multimodal.py rename to sdk/python/haxen_sdk/multimodal.py diff --git a/sdk/python/brain_sdk/multimodal_response.py b/sdk/python/haxen_sdk/multimodal_response.py similarity index 99% rename from sdk/python/brain_sdk/multimodal_response.py rename to sdk/python/haxen_sdk/multimodal_response.py index be890d8f..06eb000c 100644 --- a/sdk/python/brain_sdk/multimodal_response.py +++ b/sdk/python/haxen_sdk/multimodal_response.py @@ -10,7 +10,7 @@ from pathlib import Path from typing import Any, Dict, List, Optional, Union -from brain_sdk.logger import log_error, log_warn +from haxen_sdk.logger import log_error, log_warn from pydantic import BaseModel, Field diff --git a/sdk/python/brain_sdk/pydantic_utils.py b/sdk/python/haxen_sdk/pydantic_utils.py similarity index 98% rename from sdk/python/brain_sdk/pydantic_utils.py rename to sdk/python/haxen_sdk/pydantic_utils.py index ede54e67..3c5e5c49 100644 --- a/sdk/python/brain_sdk/pydantic_utils.py +++ b/sdk/python/haxen_sdk/pydantic_utils.py @@ -1,12 +1,12 @@ """ -Utility functions for automatic Pydantic model conversion in Brain SDK. +Utility functions for automatic Pydantic model conversion in Haxen SDK. Provides FastAPI-like automatic conversion of dictionary arguments to Pydantic model instances. """ import inspect from typing import Any, Union, get_args, get_origin, get_type_hints -from brain_sdk.logger import log_warn +from haxen_sdk.logger import log_warn from pydantic import BaseModel, ValidationError diff --git a/sdk/python/brain_sdk/rate_limiter.py b/sdk/python/haxen_sdk/rate_limiter.py similarity index 99% rename from sdk/python/brain_sdk/rate_limiter.py rename to sdk/python/haxen_sdk/rate_limiter.py index 6bc995b3..829e6330 100644 --- a/sdk/python/brain_sdk/rate_limiter.py +++ b/sdk/python/haxen_sdk/rate_limiter.py @@ -4,7 +4,7 @@ import random import time from typing import Any, Optional -from brain_sdk.logger import log_debug +from haxen_sdk.logger import log_debug class RateLimitError(Exception): diff --git a/sdk/python/brain_sdk/result_cache.py b/sdk/python/haxen_sdk/result_cache.py similarity index 100% rename from sdk/python/brain_sdk/result_cache.py rename to sdk/python/haxen_sdk/result_cache.py diff --git a/sdk/python/brain_sdk/router.py b/sdk/python/haxen_sdk/router.py similarity index 100% rename from sdk/python/brain_sdk/router.py rename to sdk/python/haxen_sdk/router.py diff --git a/sdk/python/brain_sdk/status.py b/sdk/python/haxen_sdk/status.py similarity index 96% rename from sdk/python/brain_sdk/status.py rename to sdk/python/haxen_sdk/status.py index afc3a85b..56987b58 100644 --- a/sdk/python/brain_sdk/status.py +++ b/sdk/python/haxen_sdk/status.py @@ -1,4 +1,4 @@ -"""Canonical execution status utilities for the Brain SDK.""" +"""Canonical execution status utilities for the Haxen SDK.""" from __future__ import annotations diff --git a/sdk/python/brain_sdk/types.py b/sdk/python/haxen_sdk/types.py similarity index 99% rename from sdk/python/brain_sdk/types.py rename to sdk/python/haxen_sdk/types.py index e06d4069..989df0fe 100644 --- a/sdk/python/brain_sdk/types.py +++ b/sdk/python/haxen_sdk/types.py @@ -82,7 +82,7 @@ def to_dict(self) -> Dict[str, Any]: @dataclass class ExecutionHeaders: """ - Simple helper for constructing execution headers when initiating Brain calls. + Simple helper for constructing execution headers when initiating Haxen calls. This replaces the wide workflow context structure with the minimal information required by the run-based execution pipeline. @@ -494,7 +494,7 @@ def from_env(cls, **overrides) -> "AIConfig": @dataclass class MemoryValue: - """Represents a memory value stored in the Brain system.""" + """Represents a memory value stored in the Haxen system.""" key: str data: Any diff --git a/sdk/python/brain_sdk/utils.py b/sdk/python/haxen_sdk/utils.py similarity index 100% rename from sdk/python/brain_sdk/utils.py rename to sdk/python/haxen_sdk/utils.py diff --git a/sdk/python/brain_sdk/vc_generator.py b/sdk/python/haxen_sdk/vc_generator.py similarity index 95% rename from sdk/python/brain_sdk/vc_generator.py rename to sdk/python/haxen_sdk/vc_generator.py index abd3b7ea..c06e5195 100644 --- a/sdk/python/brain_sdk/vc_generator.py +++ b/sdk/python/haxen_sdk/vc_generator.py @@ -1,5 +1,5 @@ """ -VC Generator for Brain SDK +VC Generator for Haxen SDK Handles Verifiable Credentials (VC) generation and verification for agent executions. """ @@ -58,17 +58,17 @@ class VCGenerator: - Execution VC generation - Workflow VC aggregation - VC verification - - Integration with Brain Server + - Integration with Haxen Server """ - def __init__(self, brain_server_url: str): + def __init__(self, haxen_server_url: str): """ Initialize VC Generator. Args: - brain_server_url: URL of the Brain Server + haxen_server_url: URL of the Haxen Server """ - self.brain_server_url = brain_server_url.rstrip("/") + self.haxen_server_url = haxen_server_url.rstrip("/") self.enabled = False def set_enabled(self, enabled: bool): @@ -126,9 +126,9 @@ def generate_execution_vc( "duration_ms": duration_ms, } - # Send VC generation request to Brain Server + # Send VC generation request to Haxen Server response = requests.post( - f"{self.brain_server_url}/api/v1/execution/vc", json=vc_data, timeout=10 + f"{self.haxen_server_url}/api/v1/execution/vc", json=vc_data, timeout=10 ) if response.status_code == 200: @@ -161,7 +161,7 @@ def verify_vc(self, vc_document: Dict[str, Any]) -> Optional[Dict[str, Any]]: verification_data = {"vc_document": vc_document} response = requests.post( - f"{self.brain_server_url}/api/v1/did/verify", + f"{self.haxen_server_url}/api/v1/did/verify", json=verification_data, timeout=10, ) @@ -190,7 +190,7 @@ def get_workflow_vc_chain(self, workflow_id: str) -> Optional[Dict[str, Any]]: """ try: response = requests.get( - f"{self.brain_server_url}/api/v1/did/workflow/{workflow_id}/vc-chain", + f"{self.haxen_server_url}/api/v1/did/workflow/{workflow_id}/vc-chain", timeout=10, ) @@ -227,7 +227,7 @@ def create_workflow_vc( } response = requests.post( - f"{self.brain_server_url}/api/v1/did/workflow/{workflow_id}/vc", + f"{self.haxen_server_url}/api/v1/did/workflow/{workflow_id}/vc", json=workflow_data, timeout=10, ) @@ -261,7 +261,7 @@ def export_vcs( params = filters or {} response = requests.get( - f"{self.brain_server_url}/api/v1/did/export/vcs", + f"{self.haxen_server_url}/api/v1/did/export/vcs", params=params, timeout=30, ) diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml index 7ef3731e..5aed4021 100644 --- a/sdk/python/pyproject.toml +++ b/sdk/python/pyproject.toml @@ -3,13 +3,13 @@ requires = ["setuptools>=45", "wheel"] build-backend = "setuptools.build_meta" [project] -name = "brain-sdk" +name = "haxen-sdk" version = "0.1.0" -description = "Python SDK for the Brain control plane" +description = "Python SDK for the Haxen control plane" readme = "README.md" license = {text = "Apache-2.0"} authors = [ - {name = "Brain Maintainers"} + {name = "Haxen Maintainers"} ] classifiers = [ "Development Status :: 4 - Beta", @@ -34,16 +34,16 @@ dependencies = [ "aiohttp>=3.8", "websockets" ] -keywords = ["brain", "sdk", "agents"] +keywords = ["haxen", "sdk", "agents"] [project.urls] -Homepage = "https://github.com/your-org/brain" -Documentation = "https://github.com/your-org/brain/tree/main/docs" -Issues = "https://github.com/your-org/brain/issues" +Homepage = "https://github.com/your-org/haxen" +Documentation = "https://github.com/your-org/haxen/tree/main/docs" +Issues = "https://github.com/your-org/haxen/issues" [tool.setuptools.packages.find] where = ["."] -include = ["brain_sdk*"] +include = ["haxen_sdk*"] exclude = ["tests*", "examples*"] [project.optional-dependencies] @@ -72,17 +72,17 @@ markers = [ "integration: tests that can touch network/services", "mcp: tests that exercise MCP/network interactions" ] -addopts = "-ra -q -m \"not mcp\" --strict-markers --strict-config --cov=brain_sdk.client --cov=brain_sdk.agent_brain --cov=brain_sdk.execution_context --cov=brain_sdk.execution_state --cov=brain_sdk.memory --cov=brain_sdk.rate_limiter --cov=brain_sdk.result_cache --cov-report=term-missing:skip-covered" +addopts = "-ra -q -m \"not mcp\" --strict-markers --strict-config --cov=haxen_sdk.client --cov=haxen_sdk.agent_haxen --cov=haxen_sdk.execution_context --cov=haxen_sdk.execution_state --cov=haxen_sdk.memory --cov=haxen_sdk.rate_limiter --cov=haxen_sdk.result_cache --cov-report=term-missing:skip-covered" asyncio_mode = "auto" [tool.coverage.run] -source = ["brain_sdk"] +source = ["haxen_sdk"] omit = [ - "brain_sdk/agent_mcp.py", - "brain_sdk/dynamic_skills.py", - "brain_sdk/mcp_client.py", - "brain_sdk/mcp_manager.py", - "brain_sdk/mcp_stdio_bridge.py", - "brain_sdk/logger.py", - "brain_sdk/types.py", + "haxen_sdk/agent_mcp.py", + "haxen_sdk/dynamic_skills.py", + "haxen_sdk/mcp_client.py", + "haxen_sdk/mcp_manager.py", + "haxen_sdk/mcp_stdio_bridge.py", + "haxen_sdk/logger.py", + "haxen_sdk/types.py", ] diff --git a/sdk/python/requirements-dev.txt b/sdk/python/requirements-dev.txt index 5154627f..f68b782c 100644 --- a/sdk/python/requirements-dev.txt +++ b/sdk/python/requirements-dev.txt @@ -1,4 +1,4 @@ -# Development/test dependencies for Brain SDK (Python 3.8+) +# Development/test dependencies for Haxen SDK (Python 3.8+) # Install with: pip install -r requirements-dev.txt pytest>=7.4,<9 pytest-asyncio>=0.21,<0.24 diff --git a/sdk/python/tests/conftest.py b/sdk/python/tests/conftest.py index 274d54cb..b758d2a0 100644 --- a/sdk/python/tests/conftest.py +++ b/sdk/python/tests/conftest.py @@ -1,4 +1,4 @@ -# Pytest configuration and fixtures for Brain SDK tests +# Pytest configuration and fixtures for Haxen SDK tests """ Shared fixtures used by the actively supported open-source test suite. The helpers here focus on deterministic behaviour (frozen time, env patching, @@ -21,8 +21,8 @@ import responses as responses_lib from freezegun import freeze_time -from brain_sdk.agent import Agent -from brain_sdk.types import AIConfig, MemoryConfig +from haxen_sdk.agent import Agent +from haxen_sdk.types import AIConfig, MemoryConfig # Optional imports guarded for test envs try: @@ -340,9 +340,9 @@ def _completion_alias(**kwargs): return LiteLLMMockController(module=fake) -class BrainHTTPMocks: +class HaxenHTTPMocks: """ - Helper wrapper that registers common Brain server endpoints on both: + Helper wrapper that registers common Haxen server endpoints on both: - httpx (via respx) - requests (via responses) @@ -443,9 +443,9 @@ def mock_memory_list(self, keys: List[str], status: int = 200): @pytest.fixture -def http_mocks() -> BrainHTTPMocks: +def http_mocks() -> HaxenHTTPMocks: """ - Returns a helper for mocking Brain server endpoints on both httpx and requests. + Returns a helper for mocking Haxen server endpoints on both httpx and requests. Note: This works in concert with the autouse respx/responses wrappers already defined @@ -455,9 +455,9 @@ def http_mocks() -> BrainHTTPMocks: def test_execute_headers_propagation(http_mocks, workflow_context): ctx, headers = workflow_context # minimal by default http_mocks.mock_execute("n.reasoner", json={"result": {"ok": True}}) - # ... call BrainClient.execute(...), ensure headers were passed ... + # ... call HaxenClient.execute(...), ensure headers were passed ... """ - return BrainHTTPMocks() + return HaxenHTTPMocks() # ---------------------------- 4) Sample Agent Fixture ---------------------------- @@ -492,7 +492,7 @@ def test_callback_prefers_env(mock_container_detection): mock_container_detection(is_container=False) ... """ - from brain_sdk import agent as agent_mod + from haxen_sdk import agent as agent_mod def _apply(is_container: bool = False): monkeypatch.setattr( @@ -513,7 +513,7 @@ def test_local_ip_fallback(mock_ip_detection, env_patch): env_patch.unset("AGENT_CALLBACK_URL") ... """ - from brain_sdk import agent as agent_mod + from haxen_sdk import agent as agent_mod def _apply(container_ip: Optional[str] = None, local_ip: Optional[str] = None): monkeypatch.setattr( @@ -551,7 +551,7 @@ def test_agent_init(sample_agent): agent = Agent( node_id="test-node", - brain_server="http://localhost:8080", + haxen_server="http://localhost:8080", version="0.0.0", ai_config=sample_ai_config, memory_config=MemoryConfig( @@ -567,7 +567,7 @@ def test_agent_init(sample_agent): @pytest.fixture def fake_server(monkeypatch, request): """ - Spins up an in-process FastAPI mock server and routes BrainClient calls to it WITHOUT real sockets. + Spins up an in-process FastAPI mock server and routes HaxenClient calls to it WITHOUT real sockets. This is suitable for contract tests while keeping network isolation. Endpoints: @@ -579,7 +579,7 @@ def fake_server(monkeypatch, request): How it works: - Patches httpx.AsyncClient to use httpx.ASGITransport against the in-process FastAPI app. - - BrainClient(async) calls are transparently routed; no sockets required. + - HaxenClient(async) calls are transparently routed; no sockets required. - requests.* fallbacks are NOT routed here; rely on responses/respx for those. Returns: @@ -591,7 +591,7 @@ def fake_server(monkeypatch, request): if FastAPI is None or httpx is None: pytest.skip("fastapi/httpx are required for fake_server fixture") - app = FastAPI(title="Brain Fake Server") + app = FastAPI(title="Haxen Fake Server") memory_store: Dict[str, Any] = {} @@ -609,7 +609,7 @@ async def execute_target(target: str, payload: Dict[str, Any]): "result": {"echo": payload.get("input", {}), "target": target}, "metadata": { "execution_id": "exec_" + uuid.uuid4().hex[:8], - "brain_request_id": "req_" + uuid.uuid4().hex[:8], + "haxen_request_id": "req_" + uuid.uuid4().hex[:8], "agent_node_id": target.split(".")[0] if "." in target else "node", "duration_ms": 12, "timestamp": "2024-01-01T00:00:00Z", @@ -673,7 +673,7 @@ def _patched_async_client(*args, **kwargs): # ---------------------------- Notes and Cross-Cutting Concerns ---------------------------- # - Agent.__init__ callback URL resolution is exercised via env_patch + mock_container_detection + mock_ip_detection -# - BrainClient request/header propagation is covered by http_mocks and fake_server +# - HaxenClient request/header propagation is covered by http_mocks and fake_server # - MemoryClient serialization and HTTP fallback paths are supported by http_mocks and fake_server # - AgentAI model limits caching and message trimming rely on litellm_mock + sample_ai_config # - AIConfig parameter merging and fallback logic can be tested via sample_ai_config overrides @@ -696,11 +696,11 @@ def _apply(**values): @pytest.fixture def dummy_headers(): - """Baseline execution headers consumed by memory/brain client tests.""" + """Baseline execution headers consumed by memory/haxen client tests.""" return { "X-Workflow-ID": "wf-test", "X-Execution-ID": "exec-test", - "X-Brain-Request-ID": "req-test", + "X-Haxen-Request-ID": "req-test", } diff --git a/sdk/python/tests/helpers.py b/sdk/python/tests/helpers.py index afa19d29..8261f878 100644 --- a/sdk/python/tests/helpers.py +++ b/sdk/python/tests/helpers.py @@ -1,4 +1,4 @@ -"""Shared testing utilities for Brain SDK unit tests.""" +"""Shared testing utilities for Haxen SDK unit tests.""" from __future__ import annotations @@ -8,11 +8,11 @@ from types import SimpleNamespace from typing import Any, Dict, List, Optional, Tuple -from brain_sdk.types import AgentStatus, HeartbeatData +from haxen_sdk.types import AgentStatus, HeartbeatData -class DummyBrainClient: - """Simple in-memory brain client used to capture registration calls.""" +class DummyHaxenClient: + """Simple in-memory haxen client used to capture registration calls.""" def __init__(self): self.register_calls: List[Dict[str, Any]] = [] @@ -59,14 +59,14 @@ class StubAgent: """Light-weight stand-in for Agent used across module tests.""" node_id: str = "stub-node" - brain_server: str = "http://brain" + haxen_server: str = "http://haxen" callback_url: Optional[str] = None base_url: Optional[str] = None version: str = "0.0.0" dev_mode: bool = False ai_config: Any = None async_config: Any = None - client: DummyBrainClient = field(default_factory=DummyBrainClient) + client: DummyHaxenClient = field(default_factory=DummyHaxenClient) did_manager: Any = None mcp_handler: Any = field( default_factory=lambda: type( @@ -75,7 +75,7 @@ class StubAgent: ) reasoners: List[Dict[str, Any]] = field(default_factory=list) skills: List[Dict[str, Any]] = field(default_factory=list) - brain_connected: bool = True + haxen_connected: bool = True _current_status: AgentStatus = AgentStatus.STARTING callback_candidates: List[str] = field(default_factory=list) @@ -140,7 +140,7 @@ def _apply_discovery_response(self, payload: Optional[Dict[str, Any]]) -> None: class DummyAsyncExecutionManager: - """Simple async execution manager used in tests for BrainClient async flows.""" + """Simple async execution manager used in tests for HaxenClient async flows.""" def __init__(self): self.submissions: List[Dict[str, Any]] = [] @@ -193,7 +193,7 @@ def set_event_stream_headers(self, headers: Optional[Dict[str, str]]): __all__ = [ - "DummyBrainClient", + "DummyHaxenClient", "DummyAsyncExecutionManager", "StubAgent", "create_test_agent", @@ -206,32 +206,32 @@ def create_test_agent( node_id: str = "test-agent", callback_url: Optional[str] = None, dev_mode: bool = False, -) -> Tuple[Any, DummyBrainClient]: +) -> Tuple[Any, DummyHaxenClient]: """Construct a fully initialized Agent with key dependencies stubbed out. This helper isolates network-bound components so functional tests can exercise - FastAPI routing, workflow notifications, and Brain registration without + FastAPI routing, workflow notifications, and Haxen registration without touching external services. """ - from brain_sdk.agent import Agent - from brain_sdk.agent_workflow import AgentWorkflow + from haxen_sdk.agent import Agent + from haxen_sdk.agent_workflow import AgentWorkflow memory_store: Dict[str, Any] = {} - class _FakeBrainClient(DummyBrainClient): + class _FakeHaxenClient(DummyHaxenClient): def __init__(self, base_url: str, async_config: Any): super().__init__() self.base_url = base_url self.api_base = f"{base_url}/api/v1" self.async_config = async_config - def _brain_client_factory(base_url: str, async_config: Any) -> _FakeBrainClient: - return _FakeBrainClient(base_url, async_config) + def _haxen_client_factory(base_url: str, async_config: Any) -> _FakeHaxenClient: + return _FakeHaxenClient(base_url, async_config) class _FakeMemoryClient: - def __init__(self, brain_client: Any, execution_context: Any): - self.brain_client = brain_client + def __init__(self, haxen_client: Any, execution_context: Any): + self.haxen_client = haxen_client self.execution_context = execution_context async def set(self, key: str, data: Any, scope: Optional[str] = None) -> None: @@ -287,8 +287,8 @@ def __init__(self, *args, **kwargs): pass class _FakeDIDManager: - def __init__(self, brain_server: str, node: str): - self.brain_server = brain_server + def __init__(self, haxen_server: str, node: str): + self.haxen_server = haxen_server self.node_id = node self.registered: Dict[str, Any] = {} @@ -390,17 +390,17 @@ async def _noop_fire_and_forget_update(self, payload: Dict[str, Any]) -> None: events.append(("update", payload)) self.agent._captured_workflow_events = events - monkeypatch.setattr("brain_sdk.agent.BrainClient", _brain_client_factory) - monkeypatch.setattr("brain_sdk.agent.MemoryClient", _FakeMemoryClient) - monkeypatch.setattr("brain_sdk.agent.MemoryEventClient", _FakeMemoryEventClient) - monkeypatch.setattr("brain_sdk.agent.AgentMCP", _FakeAgentMCP) - monkeypatch.setattr("brain_sdk.agent.MCPManager", _FakeMCPManager) - monkeypatch.setattr("brain_sdk.agent.MCPClientRegistry", _FakeMCPClientRegistry) + monkeypatch.setattr("haxen_sdk.agent.HaxenClient", _haxen_client_factory) + monkeypatch.setattr("haxen_sdk.agent.MemoryClient", _FakeMemoryClient) + monkeypatch.setattr("haxen_sdk.agent.MemoryEventClient", _FakeMemoryEventClient) + monkeypatch.setattr("haxen_sdk.agent.AgentMCP", _FakeAgentMCP) + monkeypatch.setattr("haxen_sdk.agent.MCPManager", _FakeMCPManager) + monkeypatch.setattr("haxen_sdk.agent.MCPClientRegistry", _FakeMCPClientRegistry) monkeypatch.setattr( - "brain_sdk.agent.DynamicMCPSkillManager", _FakeDynamicSkillManager + "haxen_sdk.agent.DynamicMCPSkillManager", _FakeDynamicSkillManager ) - monkeypatch.setattr("brain_sdk.agent.DIDManager", _FakeDIDManager) - monkeypatch.setattr("brain_sdk.agent.VCGenerator", _FakeVCGenerator) + monkeypatch.setattr("haxen_sdk.agent.DIDManager", _FakeDIDManager) + monkeypatch.setattr("haxen_sdk.agent.VCGenerator", _FakeVCGenerator) monkeypatch.setattr( AgentWorkflow, "notify_call_start", _record_call_start, raising=False ) @@ -419,7 +419,7 @@ async def _noop_fire_and_forget_update(self, payload: Dict[str, Any]) -> None: agent = Agent( node_id=node_id, - brain_server="http://brain", + haxen_server="http://haxen", version="1.2.3", callback_url=callback_url, dev_mode=dev_mode, diff --git a/sdk/python/tests/integration/conftest.py b/sdk/python/tests/integration/conftest.py index 4c5764a4..0b33aba0 100644 --- a/sdk/python/tests/integration/conftest.py +++ b/sdk/python/tests/integration/conftest.py @@ -18,7 +18,7 @@ import uvicorn if TYPE_CHECKING: - from brain_sdk.agent import Agent + from haxen_sdk.agent import Agent def _find_free_port() -> int: @@ -27,11 +27,11 @@ def _find_free_port() -> int: return sock.getsockname()[1] -def _write_brain_config(config_path: Path, db_path: Path, kv_path: Path) -> None: +def _write_haxen_config(config_path: Path, db_path: Path, kv_path: Path) -> None: db_uri = db_path.as_posix() kv_uri = kv_path.as_posix() config_content = f""" -brain: +haxen: port: 0 mode: "local" request_timeout: 60s @@ -59,23 +59,23 @@ def _write_brain_config(config_path: Path, db_path: Path, kv_path: Path) -> None @dataclass -class BrainServerInfo: +class HaxenServerInfo: base_url: str port: int - brain_home: Path + haxen_home: Path @pytest.fixture(scope="session") -def brain_binary(tmp_path_factory: pytest.TempPathFactory) -> Path: +def haxen_binary(tmp_path_factory: pytest.TempPathFactory) -> Path: repo_root = Path(__file__).resolve().parents[4] - brain_go_root = repo_root / "apps" / "platform" / "brain" - if not brain_go_root.exists(): - pytest.skip("Brain server sources not available in this checkout") - build_dir = tmp_path_factory.mktemp("brain-server-bin") - binary_name = "brain-test-server.exe" if os.name == "nt" else "brain-test-server" + haxen_go_root = repo_root / "apps" / "platform" / "haxen" + if not haxen_go_root.exists(): + pytest.skip("Haxen server sources not available in this checkout") + build_dir = tmp_path_factory.mktemp("haxen-server-bin") + binary_name = "haxen-test-server.exe" if os.name == "nt" else "haxen-test-server" binary_path = build_dir / binary_name - releases_dir = brain_go_root / "dist" / "releases" + releases_dir = haxen_go_root / "dist" / "releases" os_part = sys.platform if os_part.startswith("darwin"): os_part = "darwin" @@ -95,11 +95,11 @@ def brain_binary(tmp_path_factory: pytest.TempPathFactory) -> Path: prebuilt_path: Optional[Path] = None if os_part: - candidate = releases_dir / f"brain-{os_part}-{arch_part}" + candidate = releases_dir / f"haxen-{os_part}-{arch_part}" if candidate.exists(): prebuilt_path = candidate elif os_part == "darwin": - universal = releases_dir / "brain-darwin-arm64" + universal = releases_dir / "haxen-darwin-arm64" if universal.exists(): prebuilt_path = universal @@ -108,30 +108,30 @@ def brain_binary(tmp_path_factory: pytest.TempPathFactory) -> Path: binary_path.chmod(0o755) return binary_path - build_cmd = ["go", "build", "-o", str(binary_path), "./cmd/brain"] + build_cmd = ["go", "build", "-o", str(binary_path), "./cmd/haxen"] env = os.environ.copy() env["GOCACHE"] = str(tmp_path_factory.mktemp("go-cache")) env["GOMODCACHE"] = str(tmp_path_factory.mktemp("go-modcache")) - subprocess.run(build_cmd, check=True, cwd=brain_go_root, env=env) + subprocess.run(build_cmd, check=True, cwd=haxen_go_root, env=env) return binary_path @pytest.fixture -def brain_server( - tmp_path_factory: pytest.TempPathFactory, brain_binary: Path -) -> Generator[BrainServerInfo, None, None]: +def haxen_server( + tmp_path_factory: pytest.TempPathFactory, haxen_binary: Path +) -> Generator[HaxenServerInfo, None, None]: repo_root = Path(__file__).resolve().parents[4] - brain_go_root = repo_root / "apps" / "platform" / "brain" + haxen_go_root = repo_root / "apps" / "platform" / "haxen" - brain_home = Path(tmp_path_factory.mktemp("brain-home")) - data_dir = brain_home / "data" + haxen_home = Path(tmp_path_factory.mktemp("haxen-home")) + data_dir = haxen_home / "data" data_dir.mkdir(parents=True, exist_ok=True) - db_path = data_dir / "brain.db" - kv_path = data_dir / "brain.bolt" - config_path = brain_home / "brain.yaml" + db_path = data_dir / "haxen.db" + kv_path = data_dir / "haxen.bolt" + config_path = haxen_home / "haxen.yaml" - _write_brain_config(config_path, db_path, kv_path) + _write_haxen_config(config_path, db_path, kv_path) port = _find_free_port() base_url = f"http://127.0.0.1:{port}" @@ -139,13 +139,13 @@ def brain_server( env = os.environ.copy() env.update( { - "BRAIN_HOME": str(brain_home), - "BRAIN_STORAGE_MODE": "local", + "HAXEN_HOME": str(haxen_home), + "HAXEN_STORAGE_MODE": "local", } ) cmd = [ - str(brain_binary), + str(haxen_binary), "server", "--backend-only", "--port", @@ -155,7 +155,7 @@ def brain_server( "--no-vc-execution", ] - log_path = brain_home / "brain.log" + log_path = haxen_home / "haxen.log" log_file = log_path.open("w") process = subprocess.Popen( @@ -163,7 +163,7 @@ def brain_server( stdout=log_file, stderr=subprocess.STDOUT, env=env, - cwd=brain_go_root, + cwd=haxen_go_root, ) try: @@ -171,7 +171,7 @@ def brain_server( deadline = time.time() + 60 while time.time() < deadline: if process.poll() is not None: - raise RuntimeError("Brain server exited before becoming healthy") + raise RuntimeError("Haxen server exited before becoming healthy") try: response = requests.get(health_url, timeout=1.0) if response.status_code == 200: @@ -180,9 +180,9 @@ def brain_server( pass time.sleep(0.5) else: - raise RuntimeError("Brain server did not become healthy in time") + raise RuntimeError("Haxen server did not become healthy in time") - yield BrainServerInfo(base_url=base_url, port=port, brain_home=brain_home) + yield HaxenServerInfo(base_url=base_url, port=port, haxen_home=haxen_home) finally: if process.poll() is None: diff --git a/sdk/python/tests/integration/test_brain_end_to_end.py b/sdk/python/tests/integration/test_haxen_end_to_end.py similarity index 78% rename from sdk/python/tests/integration/test_brain_end_to_end.py rename to sdk/python/tests/integration/test_haxen_end_to_end.py index 8c10c4f9..a45c7fc8 100644 --- a/sdk/python/tests/integration/test_brain_end_to_end.py +++ b/sdk/python/tests/integration/test_haxen_end_to_end.py @@ -4,8 +4,8 @@ import httpx import pytest -from brain_sdk.agent import Agent -from brain_sdk.types import AgentStatus +from haxen_sdk.agent import Agent +from haxen_sdk.types import AgentStatus async def _wait_for_node( @@ -18,7 +18,7 @@ async def _wait_for_node( if payload.get("id") == node_id: return payload await asyncio.sleep(0.5) - raise AssertionError(f"Node {node_id} did not appear in Brain registry") + raise AssertionError(f"Node {node_id} did not appear in Haxen registry") async def _wait_for_status( @@ -40,10 +40,10 @@ async def _wait_for_status( @pytest.mark.integration @pytest.mark.asyncio -async def test_agent_registration_and_status_propagation(brain_server, run_agent): +async def test_agent_registration_and_status_propagation(haxen_server, run_agent): agent = Agent( node_id="integration-agent-status", - brain_server=brain_server.base_url, + haxen_server=haxen_server.base_url, dev_mode=True, callback_url="http://127.0.0.1", ) @@ -54,15 +54,15 @@ async def ping() -> Dict[str, bool]: runtime = run_agent(agent) - await agent.brain_handler.register_with_brain_server(runtime.port) - assert agent.brain_connected is True + await agent.haxen_handler.register_with_haxen_server(runtime.port) + assert agent.haxen_connected is True - async with httpx.AsyncClient(base_url=brain_server.base_url, timeout=5.0) as client: + async with httpx.AsyncClient(base_url=haxen_server.base_url, timeout=5.0) as client: node = await _wait_for_node(client, agent.node_id) assert any(r["id"] == "ping" for r in node.get("reasoners", [])) agent._current_status = AgentStatus.READY - await agent.brain_handler.send_enhanced_heartbeat() + await agent.haxen_handler.send_enhanced_heartbeat() status = await _wait_for_status(client, agent.node_id, expected="ready") assert status.get("state") == "active" @@ -71,10 +71,10 @@ async def ping() -> Dict[str, bool]: @pytest.mark.integration @pytest.mark.asyncio -async def test_reasoner_execution_roundtrip(brain_server, run_agent): +async def test_reasoner_execution_roundtrip(haxen_server, run_agent): agent = Agent( node_id="integration-agent-reasoner", - brain_server=brain_server.base_url, + haxen_server=haxen_server.base_url, dev_mode=True, callback_url="http://127.0.0.1", ) @@ -85,11 +85,11 @@ async def double(value: int) -> Dict[str, int]: runtime = run_agent(agent) - await agent.brain_handler.register_with_brain_server(runtime.port) + await agent.haxen_handler.register_with_haxen_server(runtime.port) agent._current_status = AgentStatus.READY - await agent.brain_handler.send_enhanced_heartbeat() + await agent.haxen_handler.send_enhanced_heartbeat() - async with httpx.AsyncClient(base_url=brain_server.base_url, timeout=5.0) as client: + async with httpx.AsyncClient(base_url=haxen_server.base_url, timeout=5.0) as client: await _wait_for_node(client, agent.node_id) await _wait_for_status(client, agent.node_id, expected="ready") diff --git a/sdk/python/tests/test_agent_ai.py b/sdk/python/tests/test_agent_ai.py index e07ddec9..9c21eaa3 100644 --- a/sdk/python/tests/test_agent_ai.py +++ b/sdk/python/tests/test_agent_ai.py @@ -7,7 +7,7 @@ import pytest -from brain_sdk.agent_ai import AgentAI +from haxen_sdk.agent_ai import AgentAI from tests.helpers import StubAgent @@ -74,7 +74,7 @@ def setup_litellm_stub(monkeypatch): monkeypatch.setitem(sys.modules, "litellm", module) monkeypatch.setitem(sys.modules, "litellm.utils", utils_module) - monkeypatch.setattr("brain_sdk.agent_ai.litellm", module, raising=False) + monkeypatch.setattr("haxen_sdk.agent_ai.litellm", module, raising=False) return module @@ -91,7 +91,7 @@ class DummyLimiter: def __init__(self, **kwargs): created.update(kwargs) - monkeypatch.setattr("brain_sdk.agent_ai.StatelessRateLimiter", DummyLimiter) + monkeypatch.setattr("haxen_sdk.agent_ai.StatelessRateLimiter", DummyLimiter) ai = AgentAI(agent_with_ai) limiter1 = ai._get_rate_limiter() @@ -128,10 +128,10 @@ async def execute_with_retry(self, func): monkeypatch.setattr(ai, "_ensure_model_limits_cached", lambda: asyncio.sleep(0)) monkeypatch.setattr(ai, "_get_rate_limiter", lambda: DummyLimiter()) monkeypatch.setattr( - "brain_sdk.agent_ai.AgentUtils.detect_input_type", lambda value: "text" + "haxen_sdk.agent_ai.AgentUtils.detect_input_type", lambda value: "text" ) monkeypatch.setattr( - "brain_sdk.agent_ai.AgentUtils.serialize_result", lambda value: value + "haxen_sdk.agent_ai.AgentUtils.serialize_result", lambda value: value ) result = await ai.ai("Hello world") @@ -167,10 +167,10 @@ async def execute_with_retry(self, func): monkeypatch.setattr(ai, "_ensure_model_limits_cached", lambda: asyncio.sleep(0)) monkeypatch.setattr(ai, "_get_rate_limiter", lambda: limiter) monkeypatch.setattr( - "brain_sdk.agent_ai.AgentUtils.detect_input_type", lambda value: "text" + "haxen_sdk.agent_ai.AgentUtils.detect_input_type", lambda value: "text" ) monkeypatch.setattr( - "brain_sdk.agent_ai.AgentUtils.serialize_result", lambda value: value + "haxen_sdk.agent_ai.AgentUtils.serialize_result", lambda value: value ) result = await ai.ai("hello") @@ -189,10 +189,10 @@ async def test_ai_skips_rate_limiter_when_disabled(monkeypatch, agent_with_ai): ai = AgentAI(agent_with_ai) monkeypatch.setattr(ai, "_ensure_model_limits_cached", lambda: asyncio.sleep(0)) monkeypatch.setattr( - "brain_sdk.agent_ai.AgentUtils.detect_input_type", lambda value: "text" + "haxen_sdk.agent_ai.AgentUtils.detect_input_type", lambda value: "text" ) monkeypatch.setattr( - "brain_sdk.agent_ai.AgentUtils.serialize_result", lambda value: value + "haxen_sdk.agent_ai.AgentUtils.serialize_result", lambda value: value ) result = await ai.ai("hello") diff --git a/sdk/python/tests/test_agent_call.py b/sdk/python/tests/test_agent_call.py index 730a375b..0234e854 100644 --- a/sdk/python/tests/test_agent_call.py +++ b/sdk/python/tests/test_agent_call.py @@ -2,15 +2,15 @@ import pytest -from brain_sdk.agent import Agent -from brain_sdk.agent_registry import set_current_agent, clear_current_agent +from haxen_sdk.agent import Agent +from haxen_sdk.agent_registry import set_current_agent, clear_current_agent @pytest.mark.asyncio async def test_call_local_reasoner_argument_mapping(): agent = object.__new__(Agent) agent.node_id = "node" - agent.brain_connected = True + agent.haxen_connected = True agent.dev_mode = False agent.async_config = SimpleNamespace( enable_async_execution=False, fallback_to_sync=False @@ -49,7 +49,7 @@ async def local_reasoner(self, a, b, execution_context=None, extra=None): async def test_call_remote_target_uses_generic_arg_names(): agent = object.__new__(Agent) agent.node_id = "node" - agent.brain_connected = True + agent.haxen_connected = True agent.dev_mode = False agent.async_config = SimpleNamespace( enable_async_execution=False, fallback_to_sync=False @@ -78,10 +78,10 @@ async def fake_execute(target, input_data, headers): @pytest.mark.asyncio -async def test_call_raises_when_brain_disconnected(): +async def test_call_raises_when_haxen_disconnected(): agent = object.__new__(Agent) agent.node_id = "node" - agent.brain_connected = False + agent.haxen_connected = False agent.dev_mode = False agent.async_config = SimpleNamespace( enable_async_execution=False, fallback_to_sync=False diff --git a/sdk/python/tests/test_agent_core.py b/sdk/python/tests/test_agent_core.py index 6e7dfd0b..98581b89 100644 --- a/sdk/python/tests/test_agent_core.py +++ b/sdk/python/tests/test_agent_core.py @@ -4,9 +4,9 @@ import pytest -from brain_sdk.agent import Agent -from brain_sdk.agent_registry import get_current_agent_instance -from brain_sdk.execution_context import ( +from haxen_sdk.agent import Agent +from haxen_sdk.agent_registry import get_current_agent_instance +from haxen_sdk.execution_context import ( ExecutionContext, set_execution_context, reset_execution_context, @@ -16,14 +16,14 @@ def make_agent_stub(): agent = object.__new__(Agent) agent.node_id = "node" - agent.brain_server = "http://brain" + agent.haxen_server = "http://haxen" agent.dev_mode = False agent.async_config = SimpleNamespace( enable_async_execution=True, fallback_to_sync=True ) agent._async_execution_manager = None agent._current_execution_context = None - agent.client = SimpleNamespace(api_base="http://brain/api/v1") + agent.client = SimpleNamespace(api_base="http://haxen/api/v1") return agent @@ -121,7 +121,7 @@ async def text(self_inner): ClientTimeout=DummyTimeout, ClientSession=DummySession ) monkeypatch.setitem(sys.modules, "aiohttp", stub_aiohttp) - monkeypatch.setattr("brain_sdk.agent.aiohttp", stub_aiohttp) + monkeypatch.setattr("haxen_sdk.agent.aiohttp", stub_aiohttp) context = SimpleNamespace(to_headers=lambda: {"X-Workflow-ID": "wf"}) monkeypatch.setattr(agent, "_get_current_execution_context", lambda: context) @@ -142,6 +142,6 @@ def create_task(self, coro): agent.note("hello", tags=["debug"]) await asyncio.gather(*tasks) - assert called["url"].startswith("http://brain/api/ui/v1") + assert called["url"].startswith("http://haxen/api/ui/v1") assert called["json"]["message"] == "hello" assert called["json"]["tags"] == ["debug"] diff --git a/sdk/python/tests/test_agent_brain.py b/sdk/python/tests/test_agent_haxen.py similarity index 58% rename from sdk/python/tests/test_agent_brain.py rename to sdk/python/tests/test_agent_haxen.py index d1010d07..5645609a 100644 --- a/sdk/python/tests/test_agent_brain.py +++ b/sdk/python/tests/test_agent_haxen.py @@ -3,135 +3,135 @@ import pytest import requests -from brain_sdk.agent_brain import AgentBrain -from tests.helpers import StubAgent, DummyBrainClient +from haxen_sdk.agent_haxen import AgentHaxen +from tests.helpers import StubAgent, DummyHaxenClient @pytest.mark.asyncio -async def test_register_with_brain_server_sets_base_url(monkeypatch): +async def test_register_with_haxen_server_sets_base_url(monkeypatch): agent = StubAgent(callback_url="agent.local", base_url=None) - agent.client = DummyBrainClient() - agent.brain_connected = False + agent.client = DummyHaxenClient() + agent.haxen_connected = False monkeypatch.setattr( - "brain_sdk.agent._resolve_callback_url", + "haxen_sdk.agent._resolve_callback_url", lambda url, port: f"http://resolved:{port}", ) monkeypatch.setattr( - "brain_sdk.agent._build_callback_candidates", + "haxen_sdk.agent._build_callback_candidates", lambda value, port, include_defaults=True: [f"http://resolved:{port}"], ) - monkeypatch.setattr("brain_sdk.agent._is_running_in_container", lambda: False) + monkeypatch.setattr("haxen_sdk.agent._is_running_in_container", lambda: False) - brain = AgentBrain(agent) - await brain.register_with_brain_server(port=8080) + haxen = AgentHaxen(agent) + await haxen.register_with_haxen_server(port=8080) assert agent.base_url == "http://resolved:8080" - assert agent.brain_connected is True + assert agent.haxen_connected is True assert agent.client.register_calls[0]["base_url"] == "http://resolved:8080" @pytest.mark.asyncio -async def test_register_with_brain_server_handles_failure(monkeypatch): +async def test_register_with_haxen_server_handles_failure(monkeypatch): async def failing_register(*args, **kwargs): raise RuntimeError("boom") agent = StubAgent(callback_url=None, base_url="http://already", dev_mode=True) - agent.client = DummyBrainClient() + agent.client = DummyHaxenClient() monkeypatch.setattr(agent.client, "register_agent", failing_register) monkeypatch.setattr( - "brain_sdk.agent._build_callback_candidates", + "haxen_sdk.agent._build_callback_candidates", lambda value, port, include_defaults=True: [], ) - monkeypatch.setattr("brain_sdk.agent._is_running_in_container", lambda: False) + monkeypatch.setattr("haxen_sdk.agent._is_running_in_container", lambda: False) - brain = AgentBrain(agent) - agent.brain_connected = True + haxen = AgentHaxen(agent) + agent.haxen_connected = True - await brain.register_with_brain_server(port=9000) - assert agent.brain_connected is False + await haxen.register_with_haxen_server(port=9000) + assert agent.haxen_connected is False @pytest.mark.asyncio -async def test_register_with_brain_updates_existing_port(monkeypatch): +async def test_register_with_haxen_updates_existing_port(monkeypatch): agent = StubAgent(callback_url=None, base_url="http://host:5000") - agent.client = DummyBrainClient() + agent.client = DummyHaxenClient() monkeypatch.setattr( - "brain_sdk.agent._build_callback_candidates", + "haxen_sdk.agent._build_callback_candidates", lambda value, port, include_defaults=True: [], ) - monkeypatch.setattr("brain_sdk.agent._is_running_in_container", lambda: False) + monkeypatch.setattr("haxen_sdk.agent._is_running_in_container", lambda: False) - brain = AgentBrain(agent) - await brain.register_with_brain_server(port=6000) + haxen = AgentHaxen(agent) + await haxen.register_with_haxen_server(port=6000) assert agent.base_url == "http://host:6000" assert agent.client.register_calls[0]["base_url"] == "http://host:6000" @pytest.mark.asyncio -async def test_register_with_brain_preserves_container_urls(monkeypatch): +async def test_register_with_haxen_preserves_container_urls(monkeypatch): agent = StubAgent( callback_url=None, base_url="http://service.railway.internal:5000", dev_mode=True, ) - agent.client = DummyBrainClient() + agent.client = DummyHaxenClient() monkeypatch.setattr( - "brain_sdk.agent._build_callback_candidates", + "haxen_sdk.agent._build_callback_candidates", lambda value, port, include_defaults=True: [], ) - monkeypatch.setattr("brain_sdk.agent._is_running_in_container", lambda: True) + monkeypatch.setattr("haxen_sdk.agent._is_running_in_container", lambda: True) - brain = AgentBrain(agent) - await brain.register_with_brain_server(port=7000) + haxen = AgentHaxen(agent) + await haxen.register_with_haxen_server(port=7000) assert agent.base_url == "http://service.railway.internal:5000" @pytest.mark.asyncio -async def test_register_with_brain_server_resolves_when_no_candidates(monkeypatch): +async def test_register_with_haxen_server_resolves_when_no_candidates(monkeypatch): agent = StubAgent(callback_url=None, base_url=None) - agent.client = DummyBrainClient() + agent.client = DummyHaxenClient() monkeypatch.setattr( - "brain_sdk.agent._build_callback_candidates", lambda *a, **k: [] + "haxen_sdk.agent._build_callback_candidates", lambda *a, **k: [] ) monkeypatch.setattr( - "brain_sdk.agent._resolve_callback_url", + "haxen_sdk.agent._resolve_callback_url", lambda url, port: f"http://resolved:{port}", ) - monkeypatch.setattr("brain_sdk.agent._is_running_in_container", lambda: False) + monkeypatch.setattr("haxen_sdk.agent._is_running_in_container", lambda: False) - brain = AgentBrain(agent) - await brain.register_with_brain_server(port=7100) + haxen = AgentHaxen(agent) + await haxen.register_with_haxen_server(port=7100) assert agent.base_url == "http://resolved:7100" - assert agent.brain_connected is True + assert agent.haxen_connected is True @pytest.mark.asyncio -async def test_register_with_brain_server_reorders_candidates(monkeypatch): +async def test_register_with_haxen_server_reorders_candidates(monkeypatch): agent = StubAgent(callback_url=None, base_url="http://preferred:8000") - agent.client = DummyBrainClient() + agent.client = DummyHaxenClient() agent.callback_candidates = ["http://other:8000", "http://preferred:8000"] monkeypatch.setattr( - "brain_sdk.agent._build_callback_candidates", + "haxen_sdk.agent._build_callback_candidates", lambda value, port, include_defaults=True: agent.callback_candidates, ) - monkeypatch.setattr("brain_sdk.agent._is_running_in_container", lambda: False) + monkeypatch.setattr("haxen_sdk.agent._is_running_in_container", lambda: False) - brain = AgentBrain(agent) - await brain.register_with_brain_server(port=8000) + haxen = AgentHaxen(agent) + await haxen.register_with_haxen_server(port=8000) assert agent.callback_candidates[0] == "http://preferred:8000" @pytest.mark.asyncio -async def test_register_with_brain_server_propagates_request_exception(monkeypatch): +async def test_register_with_haxen_server_propagates_request_exception(monkeypatch): class DummyResponse: def __init__(self): self.status_code = 503 @@ -144,49 +144,49 @@ async def failing_register(*args, **kwargs): raise exception agent = StubAgent(callback_url=None, base_url="http://already", dev_mode=False) - agent.client = DummyBrainClient() + agent.client = DummyHaxenClient() monkeypatch.setattr(agent.client, "register_agent", failing_register) monkeypatch.setattr( - "brain_sdk.agent._build_callback_candidates", lambda *a, **k: [] + "haxen_sdk.agent._build_callback_candidates", lambda *a, **k: [] ) monkeypatch.setattr( - "brain_sdk.agent._resolve_callback_url", lambda url, port: "http://already" + "haxen_sdk.agent._resolve_callback_url", lambda url, port: "http://already" ) - monkeypatch.setattr("brain_sdk.agent._is_running_in_container", lambda: False) + monkeypatch.setattr("haxen_sdk.agent._is_running_in_container", lambda: False) - brain = AgentBrain(agent) + haxen = AgentHaxen(agent) with pytest.raises(requests.exceptions.RequestException): - await brain.register_with_brain_server(port=9001) - assert agent.brain_connected is False + await haxen.register_with_haxen_server(port=9001) + assert agent.haxen_connected is False @pytest.mark.asyncio -async def test_register_with_brain_server_unsuccessful_response(monkeypatch): +async def test_register_with_haxen_server_unsuccessful_response(monkeypatch): agent = StubAgent(callback_url=None, base_url="http://host:5000") - agent.client = DummyBrainClient() + agent.client = DummyHaxenClient() async def register_returns_false(*args, **kwargs): return False, None monkeypatch.setattr(agent.client, "register_agent", register_returns_false) monkeypatch.setattr( - "brain_sdk.agent._build_callback_candidates", lambda *a, **k: [] + "haxen_sdk.agent._build_callback_candidates", lambda *a, **k: [] ) monkeypatch.setattr( - "brain_sdk.agent._resolve_callback_url", lambda url, port: "http://host:5000" + "haxen_sdk.agent._resolve_callback_url", lambda url, port: "http://host:5000" ) - monkeypatch.setattr("brain_sdk.agent._is_running_in_container", lambda: False) + monkeypatch.setattr("haxen_sdk.agent._is_running_in_container", lambda: False) - brain = AgentBrain(agent) - await brain.register_with_brain_server(port=5000) - assert agent.brain_connected is False + haxen = AgentHaxen(agent) + await haxen.register_with_haxen_server(port=5000) + assert agent.haxen_connected is False @pytest.mark.asyncio -async def test_register_with_brain_applies_discovery_payload(monkeypatch): +async def test_register_with_haxen_applies_discovery_payload(monkeypatch): from tests.helpers import create_test_agent - agent, brain_client = create_test_agent(monkeypatch) + agent, haxen_client = create_test_agent(monkeypatch) agent.callback_candidates = [] async def fake_register(node_id, reasoners, skills, base_url, discovery=None): @@ -197,14 +197,14 @@ async def fake_register(node_id, reasoners, skills, base_url, discovery=None): }, } - monkeypatch.setattr(brain_client, "register_agent", fake_register) + monkeypatch.setattr(haxen_client, "register_agent", fake_register) monkeypatch.setattr( - "brain_sdk.agent._build_callback_candidates", + "haxen_sdk.agent._build_callback_candidates", lambda value, port, include_defaults=True: [f"http://detected:{port}"], ) - monkeypatch.setattr("brain_sdk.agent._is_running_in_container", lambda: False) + monkeypatch.setattr("haxen_sdk.agent._is_running_in_container", lambda: False) - await agent.brain_handler.register_with_brain_server(port=9000) + await agent.haxen_handler.register_with_haxen_server(port=9000) assert agent.base_url == "https://public:9000" assert agent.callback_candidates[0] == "https://public:9000" @@ -213,7 +213,7 @@ async def fake_register(node_id, reasoners, skills, base_url, discovery=None): def test_send_heartbeat(monkeypatch): agent = StubAgent() - brain = AgentBrain(agent) + haxen = AgentHaxen(agent) calls = {} @@ -227,62 +227,62 @@ class Dummy: return Dummy() monkeypatch.setattr("requests.post", fake_post) - brain.send_heartbeat() + haxen.send_heartbeat() assert calls["url"].endswith(f"/api/v1/nodes/{agent.node_id}/heartbeat") def test_send_heartbeat_warns_on_non_200(monkeypatch): agent = StubAgent() - agent.brain_connected = True - brain = AgentBrain(agent) + agent.haxen_connected = True + haxen = AgentHaxen(agent) class Dummy: status_code = 500 text = "error" monkeypatch.setattr("requests.post", lambda *a, **k: Dummy()) - brain.send_heartbeat() + haxen.send_heartbeat() @pytest.mark.asyncio async def test_enhanced_heartbeat_returns_false_when_disconnected(): agent = StubAgent() - brain = AgentBrain(agent) - agent.brain_connected = False - assert await brain.send_enhanced_heartbeat() is False + haxen = AgentHaxen(agent) + agent.haxen_connected = False + assert await haxen.send_enhanced_heartbeat() is False def test_start_and_stop_heartbeat(monkeypatch): agent = StubAgent() - brain = AgentBrain(agent) + haxen = AgentHaxen(agent) called = [] def fake_worker(interval): called.append(interval) - monkeypatch.setattr(brain, "heartbeat_worker", fake_worker) + monkeypatch.setattr(haxen, "heartbeat_worker", fake_worker) - brain.start_heartbeat(interval=1) + haxen.start_heartbeat(interval=1) assert isinstance(agent._heartbeat_thread, threading.Thread) - brain.stop_heartbeat() + haxen.stop_heartbeat() @pytest.mark.asyncio async def test_enhanced_heartbeat_and_shutdown(monkeypatch): agent = StubAgent() - agent.client = DummyBrainClient() + agent.client = DummyHaxenClient() agent.mcp_handler = type( "MCP", (), {"_get_mcp_server_health": lambda self: ["mcp"]} )() agent.dev_mode = True - brain = AgentBrain(agent) + haxen = AgentHaxen(agent) - success = await brain.send_enhanced_heartbeat() + success = await haxen.send_enhanced_heartbeat() assert success is True assert agent.client.heartbeat_calls - success_shutdown = await brain.notify_shutdown() + success_shutdown = await haxen.notify_shutdown() assert success_shutdown is True assert agent.client.shutdown_calls == [agent.node_id] @@ -290,48 +290,48 @@ async def test_enhanced_heartbeat_and_shutdown(monkeypatch): @pytest.mark.asyncio async def test_enhanced_heartbeat_failure_returns_false(monkeypatch): agent = StubAgent() - agent.client = DummyBrainClient() - brain = AgentBrain(agent) + agent.client = DummyHaxenClient() + haxen = AgentHaxen(agent) async def boom(*args, **kwargs): raise RuntimeError("boom") monkeypatch.setattr(agent.client, "send_enhanced_heartbeat", boom) - agent.brain_connected = True + agent.haxen_connected = True agent.dev_mode = True - assert await brain.send_enhanced_heartbeat() is False + assert await haxen.send_enhanced_heartbeat() is False @pytest.mark.asyncio async def test_notify_shutdown_failure_returns_false(monkeypatch): agent = StubAgent() - agent.client = DummyBrainClient() - brain = AgentBrain(agent) + agent.client = DummyHaxenClient() + haxen = AgentHaxen(agent) async def boom(*args, **kwargs): raise RuntimeError("boom") monkeypatch.setattr(agent.client, "notify_graceful_shutdown", boom) - agent.brain_connected = True + agent.haxen_connected = True agent.dev_mode = True - assert await brain.notify_shutdown() is False + assert await haxen.notify_shutdown() is False def test_send_heartbeat_handles_error(monkeypatch): agent = StubAgent() - agent.brain_connected = True - brain = AgentBrain(agent) + agent.haxen_connected = True + haxen = AgentHaxen(agent) def boom(*args, **kwargs): raise requests.RequestException("boom") monkeypatch.setattr("requests.post", boom) - brain.send_heartbeat() + haxen.send_heartbeat() def test_start_heartbeat_skips_when_disconnected(): agent = StubAgent() - agent.brain_connected = False - brain = AgentBrain(agent) - brain.start_heartbeat() + agent.haxen_connected = False + haxen = AgentHaxen(agent) + haxen.start_heartbeat() assert agent._heartbeat_thread is None diff --git a/sdk/python/tests/test_agent_helpers.py b/sdk/python/tests/test_agent_helpers.py index 833fbf2c..8d5ec42b 100644 --- a/sdk/python/tests/test_agent_helpers.py +++ b/sdk/python/tests/test_agent_helpers.py @@ -1,4 +1,4 @@ -from brain_sdk.agent import _resolve_callback_url, _build_callback_candidates +from haxen_sdk.agent import _resolve_callback_url, _build_callback_candidates def test_resolve_callback_url_prefers_explicit_url(): @@ -23,9 +23,9 @@ def test_resolve_callback_url_handles_container_overrides(monkeypatch): monkeypatch.setenv("RAILWAY_SERVICE_NAME", "my-service") monkeypatch.setenv("RAILWAY_ENVIRONMENT", "prod") - monkeypatch.setattr("brain_sdk.agent._is_running_in_container", lambda: True) - monkeypatch.setattr("brain_sdk.agent._detect_container_ip", lambda: None) - monkeypatch.setattr("brain_sdk.agent._detect_local_ip", lambda: "10.0.0.5") + monkeypatch.setattr("haxen_sdk.agent._is_running_in_container", lambda: True) + monkeypatch.setattr("haxen_sdk.agent._detect_container_ip", lambda: None) + monkeypatch.setattr("haxen_sdk.agent._detect_local_ip", lambda: "10.0.0.5") url = _resolve_callback_url(None, port=4500) assert url == "http://my-service.railway.internal:4500" @@ -36,14 +36,14 @@ def test_resolve_callback_url_fallback_to_detected_ips(monkeypatch): monkeypatch.delenv("RAILWAY_SERVICE_NAME", raising=False) monkeypatch.delenv("RAILWAY_ENVIRONMENT", raising=False) - monkeypatch.setattr("brain_sdk.agent._is_running_in_container", lambda: True) - monkeypatch.setattr("brain_sdk.agent._detect_container_ip", lambda: "203.0.113.10") + monkeypatch.setattr("haxen_sdk.agent._is_running_in_container", lambda: True) + monkeypatch.setattr("haxen_sdk.agent._detect_container_ip", lambda: "203.0.113.10") url = _resolve_callback_url(None, port=3200) assert url == "http://203.0.113.10:3200" - monkeypatch.setattr("brain_sdk.agent._detect_container_ip", lambda: None) - monkeypatch.setattr("brain_sdk.agent._detect_local_ip", lambda: "192.168.1.2") + monkeypatch.setattr("haxen_sdk.agent._detect_container_ip", lambda: None) + monkeypatch.setattr("haxen_sdk.agent._detect_local_ip", lambda: "192.168.1.2") url = _resolve_callback_url(None, port=3201) assert url == "http://192.168.1.2:3201" @@ -51,18 +51,18 @@ def test_resolve_callback_url_fallback_to_detected_ips(monkeypatch): def test_resolve_callback_url_final_fallback(monkeypatch): monkeypatch.delenv("AGENT_CALLBACK_URL", raising=False) - monkeypatch.setattr("brain_sdk.agent._is_running_in_container", lambda: False) - monkeypatch.setattr("brain_sdk.agent._detect_local_ip", lambda: None) - monkeypatch.setattr("brain_sdk.agent.socket.gethostname", lambda: "") + monkeypatch.setattr("haxen_sdk.agent._is_running_in_container", lambda: False) + monkeypatch.setattr("haxen_sdk.agent._detect_local_ip", lambda: None) + monkeypatch.setattr("haxen_sdk.agent.socket.gethostname", lambda: "") url = _resolve_callback_url(None, port=8080) assert url in {"http://localhost:8080", "http://host.docker.internal:8080"} def test_build_callback_candidates_includes_defaults(monkeypatch): - monkeypatch.setattr("brain_sdk.agent._is_running_in_container", lambda: False) - monkeypatch.setattr("brain_sdk.agent._detect_local_ip", lambda: "192.168.1.50") - monkeypatch.setattr("brain_sdk.agent.socket.gethostname", lambda: "my-host") + monkeypatch.setattr("haxen_sdk.agent._is_running_in_container", lambda: False) + monkeypatch.setattr("haxen_sdk.agent._detect_local_ip", lambda: "192.168.1.50") + monkeypatch.setattr("haxen_sdk.agent.socket.gethostname", lambda: "my-host") candidates = _build_callback_candidates(None, 9000) diff --git a/sdk/python/tests/test_agent_integration.py b/sdk/python/tests/test_agent_integration.py index e7ea9fd3..f9f13630 100644 --- a/sdk/python/tests/test_agent_integration.py +++ b/sdk/python/tests/test_agent_integration.py @@ -4,14 +4,14 @@ import pytest from fastapi import APIRouter -from brain_sdk.router import AgentRouter +from haxen_sdk.router import AgentRouter from tests.helpers import create_test_agent @pytest.mark.asyncio async def test_agent_reasoner_routing_and_workflow(monkeypatch): - agent, brain_client = create_test_agent( + agent, haxen_client = create_test_agent( monkeypatch, callback_url="https://callback.example.com" ) @@ -38,9 +38,9 @@ async def status(): agent.include_router(router, prefix="/ops") - await agent.brain_handler.register_with_brain_server(port=9100) - assert brain_client.register_calls - registration = brain_client.register_calls[-1] + await agent.haxen_handler.register_with_haxen_server(port=9100) + assert haxen_client.register_calls + registration = haxen_client.register_calls[-1] assert registration["base_url"] == "https://callback.example.com:9100" assert registration["reasoners"][0]["id"] == "double" assert registration["skills"][0]["id"] == "annotate" @@ -165,7 +165,7 @@ async def test_callback_url_precedence_and_env(monkeypatch): explicit_agent, explicit_client = create_test_agent( monkeypatch, callback_url="https://explicit.example.com" ) - await explicit_agent.brain_handler.register_with_brain_server(port=9200) + await explicit_agent.haxen_handler.register_with_haxen_server(port=9200) assert explicit_agent.base_url == "https://explicit.example.com:9200" assert ( explicit_client.register_calls[-1]["base_url"] @@ -173,6 +173,6 @@ async def test_callback_url_precedence_and_env(monkeypatch): ) env_agent, env_client = create_test_agent(monkeypatch) - await env_agent.brain_handler.register_with_brain_server(port=9300) + await env_agent.haxen_handler.register_with_haxen_server(port=9300) assert env_agent.base_url == "https://env.example.com:9300" assert env_client.register_calls[-1]["base_url"] == "https://env.example.com:9300" diff --git a/sdk/python/tests/test_agent_networking.py b/sdk/python/tests/test_agent_networking.py index a26cf283..1ebaa4ec 100644 --- a/sdk/python/tests/test_agent_networking.py +++ b/sdk/python/tests/test_agent_networking.py @@ -2,8 +2,8 @@ import pytest -from brain_sdk import agent as agent_mod -from brain_sdk.agent import ( +from haxen_sdk import agent as agent_mod +from haxen_sdk.agent import ( ExecutionContext, _build_callback_candidates, _normalize_candidate, @@ -96,7 +96,7 @@ def test_build_callback_candidates_prefers_env(monkeypatch): monkeypatch.setattr(agent_mod, "_detect_local_ip", lambda: "10.0.0.5") monkeypatch.setattr(agent_mod.socket, "gethostname", lambda: "agent-host") monkeypatch.setenv("AGENT_CALLBACK_URL", "https://env.example") - monkeypatch.setenv("RAILWAY_SERVICE_NAME", "brain") + monkeypatch.setenv("RAILWAY_SERVICE_NAME", "haxen") monkeypatch.setenv("RAILWAY_ENVIRONMENT", "prod") candidates = _build_callback_candidates(None, 9090) diff --git a/sdk/python/tests/test_agent_registry.py b/sdk/python/tests/test_agent_registry.py index a238f868..bb849496 100644 --- a/sdk/python/tests/test_agent_registry.py +++ b/sdk/python/tests/test_agent_registry.py @@ -1,4 +1,4 @@ -from brain_sdk.agent_registry import ( +from haxen_sdk.agent_registry import ( set_current_agent, get_current_agent_instance, clear_current_agent, diff --git a/sdk/python/tests/test_agent_server.py b/sdk/python/tests/test_agent_server.py index 7aa4c0ee..70916e32 100644 --- a/sdk/python/tests/test_agent_server.py +++ b/sdk/python/tests/test_agent_server.py @@ -5,7 +5,7 @@ from types import SimpleNamespace from fastapi import FastAPI -from brain_sdk.agent_server import AgentServer +from haxen_sdk.agent_server import AgentServer def make_agent_app(): @@ -29,15 +29,15 @@ def make_agent_app(): }, )() app.dev_mode = False - app.brain_server = "http://brain" + app.haxen_server = "http://haxen" return app @pytest.mark.asyncio -async def test_setup_brain_routes_health_endpoint(): +async def test_setup_haxen_routes_health_endpoint(): app = make_agent_app() server = AgentServer(app) - server.setup_brain_routes() + server.setup_haxen_routes() async with httpx.AsyncClient( transport=httpx.ASGITransport(app=app), base_url="http://test" @@ -64,7 +64,7 @@ async def test_shutdown_endpoint_triggers_flags(): app = make_agent_app() app.dev_mode = True server = AgentServer(app) - server.setup_brain_routes() + server.setup_haxen_routes() async with httpx.AsyncClient( transport=httpx.ASGITransport(app=app), base_url="http://test" @@ -99,7 +99,7 @@ def num_threads(self): dummy_psutil = SimpleNamespace(Process=lambda: DummyProcess()) monkeypatch.setitem(sys.modules, "psutil", dummy_psutil) - server.setup_brain_routes() + server.setup_haxen_routes() async with httpx.AsyncClient( transport=httpx.ASGITransport(app=app), base_url="http://test" @@ -116,7 +116,7 @@ def num_threads(self): async def test_shutdown_immediate_path(monkeypatch): app = make_agent_app() server = AgentServer(app) - server.setup_brain_routes() + server.setup_haxen_routes() triggered = {} @@ -162,7 +162,7 @@ def get_all_status(self): manager = StubMCPManager() app.mcp_manager = manager server = AgentServer(app) - server.setup_brain_routes() + server.setup_haxen_routes() async with httpx.AsyncClient( transport=httpx.ASGITransport(app=app), base_url="http://test" diff --git a/sdk/python/tests/test_agent_utils.py b/sdk/python/tests/test_agent_utils.py index 8b5fec59..9cb0501c 100644 --- a/sdk/python/tests/test_agent_utils.py +++ b/sdk/python/tests/test_agent_utils.py @@ -1,7 +1,7 @@ import pytest from pydantic import BaseModel -from brain_sdk.agent_utils import AgentUtils +from haxen_sdk.agent_utils import AgentUtils def test_detect_input_type_and_helpers(tmp_path): diff --git a/sdk/python/tests/test_agent_workflow.py b/sdk/python/tests/test_agent_workflow.py index 8c5b0363..e1c40756 100644 --- a/sdk/python/tests/test_agent_workflow.py +++ b/sdk/python/tests/test_agent_workflow.py @@ -1,8 +1,8 @@ import pytest -from brain_sdk.agent_workflow import AgentWorkflow -from brain_sdk.execution_context import ExecutionContext -from brain_sdk.agent_registry import set_current_agent, clear_current_agent +from haxen_sdk.agent_workflow import AgentWorkflow +from haxen_sdk.execution_context import ExecutionContext +from haxen_sdk.agent_registry import set_current_agent, clear_current_agent from tests.helpers import StubAgent diff --git a/sdk/python/tests/test_agent_workflow_registration.py b/sdk/python/tests/test_agent_workflow_registration.py index 06b1dce3..9288b569 100644 --- a/sdk/python/tests/test_agent_workflow_registration.py +++ b/sdk/python/tests/test_agent_workflow_registration.py @@ -1,9 +1,9 @@ import pytest -from brain_sdk.agent_workflow import AgentWorkflow -from brain_sdk.agent_registry import set_current_agent, clear_current_agent -from brain_sdk.decorators import _execute_with_tracking -from brain_sdk.execution_context import ( +from haxen_sdk.agent_workflow import AgentWorkflow +from haxen_sdk.agent_registry import set_current_agent, clear_current_agent +from haxen_sdk.decorators import _execute_with_tracking +from haxen_sdk.execution_context import ( ExecutionContext, set_execution_context, reset_execution_context, @@ -38,7 +38,7 @@ async def _async_request(self, method, url, **kwargs): class DummyAgent: def __init__(self): self.node_id = "agent-node" - self.brain_server = "http://brain.local" + self.haxen_server = "http://haxen.local" self.client = DummyClient() self.dev_mode = False self._current_execution_context = None diff --git a/sdk/python/tests/test_ai_config.py b/sdk/python/tests/test_ai_config.py index 80e28117..b26fa55f 100644 --- a/sdk/python/tests/test_ai_config.py +++ b/sdk/python/tests/test_ai_config.py @@ -1,4 +1,4 @@ -from brain_sdk.types import AIConfig +from haxen_sdk.types import AIConfig def test_ai_config_defaults_and_to_dict(): diff --git a/sdk/python/tests/test_async_config.py b/sdk/python/tests/test_async_config.py index 68c1c0e3..93393746 100644 --- a/sdk/python/tests/test_async_config.py +++ b/sdk/python/tests/test_async_config.py @@ -1,4 +1,4 @@ -from brain_sdk.async_config import AsyncConfig +from haxen_sdk.async_config import AsyncConfig def test_async_config_validate_defaults_ok(): @@ -34,12 +34,12 @@ def test_get_poll_interval_for_age(): def test_from_environment_overrides(monkeypatch): - monkeypatch.setenv("BRAIN_ASYNC_MAX_EXECUTION_TIMEOUT", "123") - monkeypatch.setenv("BRAIN_ASYNC_BATCH_SIZE", "7") - monkeypatch.setenv("BRAIN_ASYNC_ENABLE_RESULT_CACHING", "false") - monkeypatch.setenv("BRAIN_ASYNC_ENABLE_EVENT_STREAM", "true") - monkeypatch.setenv("BRAIN_ASYNC_EVENT_STREAM_PATH", "/stream") - monkeypatch.setenv("BRAIN_ASYNC_EVENT_STREAM_RETRY_BACKOFF", "4.5") + monkeypatch.setenv("HAXEN_ASYNC_MAX_EXECUTION_TIMEOUT", "123") + monkeypatch.setenv("HAXEN_ASYNC_BATCH_SIZE", "7") + monkeypatch.setenv("HAXEN_ASYNC_ENABLE_RESULT_CACHING", "false") + monkeypatch.setenv("HAXEN_ASYNC_ENABLE_EVENT_STREAM", "true") + monkeypatch.setenv("HAXEN_ASYNC_EVENT_STREAM_PATH", "/stream") + monkeypatch.setenv("HAXEN_ASYNC_EVENT_STREAM_RETRY_BACKOFF", "4.5") cfg = AsyncConfig.from_environment() assert cfg.max_execution_timeout == 123 diff --git a/sdk/python/tests/test_async_execution_manager_paths.py b/sdk/python/tests/test_async_execution_manager_paths.py index 2f8fb9c3..6953e136 100644 --- a/sdk/python/tests/test_async_execution_manager_paths.py +++ b/sdk/python/tests/test_async_execution_manager_paths.py @@ -5,9 +5,9 @@ import pytest -from brain_sdk.async_config import AsyncConfig -from brain_sdk.async_execution_manager import AsyncExecutionManager -from brain_sdk.execution_state import ExecutionState, ExecutionStatus +from haxen_sdk.async_config import AsyncConfig +from haxen_sdk.async_execution_manager import AsyncExecutionManager +from haxen_sdk.execution_state import ExecutionState, ExecutionStatus class _DummyResponse: diff --git a/sdk/python/tests/test_client.py b/sdk/python/tests/test_client.py index efffe74b..f3498b0e 100644 --- a/sdk/python/tests/test_client.py +++ b/sdk/python/tests/test_client.py @@ -6,8 +6,8 @@ import pytest import requests -from brain_sdk.client import BrainClient -from brain_sdk.types import AgentStatus, HeartbeatData +from haxen_sdk.client import HaxenClient +from haxen_sdk.types import AgentStatus, HeartbeatData @pytest.fixture(autouse=True) @@ -64,7 +64,7 @@ async def aclose(self): Timeout=lambda *args, **kwargs: None, ) - import brain_sdk.client as client_mod + import haxen_sdk.client as client_mod monkeypatch.setitem(sys.modules, "httpx", module) client_mod.httpx = module @@ -100,12 +100,12 @@ def fake_get(url, headers=None, timeout=None): } ) - import brain_sdk.client as client_mod + import haxen_sdk.client as client_mod monkeypatch.setattr(client_mod.requests, "post", fake_post) monkeypatch.setattr(client_mod.requests, "get", fake_get) - client = BrainClient(base_url="http://example.com") + client = HaxenClient(base_url="http://example.com") result = client.execute_sync("node.reasoner", {"payload": 1}) assert result["status"] == "succeeded" @@ -143,12 +143,12 @@ def fake_get(url, headers=None, timeout=None): } ) - import brain_sdk.client as client_mod + import haxen_sdk.client as client_mod monkeypatch.setattr(client_mod.requests, "post", fake_post) monkeypatch.setattr(client_mod.requests, "get", fake_get) - client = BrainClient(base_url="http://example.com") + client = HaxenClient(base_url="http://example.com") result = client.execute_sync( "node.reasoner", {"payload": 1}, @@ -182,7 +182,7 @@ def on_request(method, url, **kwargs): install_httpx_stub(monkeypatch, on_request=on_request) - client = BrainClient(base_url="http://example.com") + client = HaxenClient(base_url="http://example.com") result = asyncio.run(client.execute("node.reasoner", {"payload": 1})) assert result["result"] == {"async": True} @@ -228,7 +228,7 @@ def fake_get(url, headers=None, timeout=None, **kwargs): } ) - import brain_sdk.client as client_mod + import haxen_sdk.client as client_mod client_mod.httpx = None monkeypatch.setattr( @@ -246,7 +246,7 @@ def fake_session_request(self, method, url, **kwargs): monkeypatch.setattr(requests.Session, "request", fake_session_request) - client = BrainClient(base_url="http://example.com") + client = HaxenClient(base_url="http://example.com") result = await client.execute("node.reasoner", {"payload": 1}) assert result["status"] == "succeeded" @@ -265,13 +265,13 @@ def on_request(method, url, **kwargs): install_httpx_stub(monkeypatch, on_request=on_request) - import brain_sdk.client as client_mod + import haxen_sdk.client as client_mod monkeypatch.setattr( client_mod.requests, "post", lambda *args, **kwargs: DummyResponse({}, 200) ) - client = BrainClient(base_url="http://example.com") + client = HaxenClient(base_url="http://example.com") heartbeat = HeartbeatData(status=AgentStatus.READY, mcp_servers=[], timestamp="now") assert await client.send_enhanced_heartbeat("node", heartbeat) is True @@ -290,11 +290,11 @@ def fake_post(url, json=None, headers=None, timeout=None): urls.append(url) return DummyResp() - import brain_sdk.client as client_mod + import haxen_sdk.client as client_mod monkeypatch.setattr(client_mod.requests, "post", fake_post) - client = BrainClient(base_url="http://example.com") + client = HaxenClient(base_url="http://example.com") heartbeat = HeartbeatData(status=AgentStatus.READY, mcp_servers=[], timestamp="now") assert client.send_enhanced_heartbeat_sync("node", heartbeat) is True @@ -329,13 +329,13 @@ def fake_get(url, **kwargs): calls.setdefault("get", []).append(url) return DummyResp({"nodes": ["n1"]}) - import brain_sdk.client as client_mod + import haxen_sdk.client as client_mod monkeypatch.setattr(client_mod.requests, "post", fake_post) monkeypatch.setattr(client_mod.requests, "put", fake_put) monkeypatch.setattr(client_mod.requests, "get", fake_get) - client = BrainClient(base_url="http://example.com") + client = HaxenClient(base_url="http://example.com") assert client.register_node({"id": "n1"}) == {"ok": True} assert client.update_health("n1", {"status": "up"}) == {"status": "updated"} assert client.get_nodes() == {"nodes": ["n1"]} @@ -355,7 +355,7 @@ def on_request(method, url, **kwargs): install_httpx_stub(monkeypatch, on_request=on_request) - client = BrainClient(base_url="http://example.com") + client = HaxenClient(base_url="http://example.com") ok, payload = await client.register_agent("node-1", [], [], base_url="http://agent") assert ok is True assert payload == {} diff --git a/sdk/python/tests/test_client_lifecycle.py b/sdk/python/tests/test_client_lifecycle.py index a9c69886..989843e5 100644 --- a/sdk/python/tests/test_client_lifecycle.py +++ b/sdk/python/tests/test_client_lifecycle.py @@ -2,8 +2,8 @@ import sys import types -from brain_sdk.client import BrainClient -from brain_sdk.types import AgentStatus, HeartbeatData +from haxen_sdk.client import HaxenClient +from haxen_sdk.types import AgentStatus, HeartbeatData class DummyResponse: @@ -28,11 +28,11 @@ def ok_post(url, json, headers, timeout): sent["calls"] += 1 return DummyResponse(200) - import brain_sdk.client as client_mod + import haxen_sdk.client as client_mod monkeypatch.setattr(client_mod.requests, "post", ok_post) - bc = BrainClient(base_url="http://example") + bc = HaxenClient(base_url="http://example") hb = HeartbeatData(status=AgentStatus.READY, mcp_servers=[], timestamp="now") assert bc.send_enhanced_heartbeat_sync("node1", hb) is True @@ -44,13 +44,13 @@ def bad_post(url, json, headers, timeout): def test_notify_graceful_shutdown_sync(monkeypatch): - import brain_sdk.client as client_mod + import haxen_sdk.client as client_mod def ok_post(url, headers, timeout): return DummyResponse(200) monkeypatch.setattr(client_mod.requests, "post", ok_post) - bc = BrainClient(base_url="http://example") + bc = HaxenClient(base_url="http://example") assert bc.notify_graceful_shutdown_sync("node1") is True def bad_post(url, headers, timeout): @@ -61,8 +61,8 @@ def bad_post(url, headers, timeout): def test_register_agent_with_status_async(monkeypatch): - # Provide a dummy httpx module that BrainClient will use - from brain_sdk import client as client_mod + # Provide a dummy httpx module that HaxenClient will use + from haxen_sdk import client as client_mod class DummyAsyncClient: def __init__(self, *args, **kwargs): @@ -90,7 +90,7 @@ async def aclose(self): raising=False, ) - bc = BrainClient(base_url="http://example") + bc = HaxenClient(base_url="http://example") async def run(): return await bc.register_agent_with_status( diff --git a/sdk/python/tests/test_client_unit.py b/sdk/python/tests/test_client_unit.py index 88d00338..e23c2c74 100644 --- a/sdk/python/tests/test_client_unit.py +++ b/sdk/python/tests/test_client_unit.py @@ -2,7 +2,7 @@ import pytest -from brain_sdk.client import BrainClient +from haxen_sdk.client import HaxenClient class DummyContext: @@ -22,7 +22,7 @@ def set_event_stream_headers(self, headers): def test_generate_id_prefix_and_uniqueness(): - client = BrainClient() + client = HaxenClient() first = client._generate_id("exec") second = client._generate_id("exec") assert first.startswith("exec_") @@ -32,7 +32,7 @@ def test_generate_id_prefix_and_uniqueness(): def test_get_headers_with_context_merges_workflow_headers(): - client = BrainClient() + client = HaxenClient() client._current_workflow_context = DummyContext({"X-Workflow-ID": "wf-1"}) combined = client._get_headers_with_context({"Authorization": "Bearer token"}) @@ -42,7 +42,7 @@ def test_get_headers_with_context_merges_workflow_headers(): def test_build_event_stream_headers_filters_keys(): - client = BrainClient() + client = HaxenClient() headers = { "Authorization": "Bearer token", "X-Custom": "value", @@ -61,7 +61,7 @@ def test_build_event_stream_headers_filters_keys(): def test_maybe_update_event_stream_headers_uses_context_when_enabled(): - client = BrainClient() + client = HaxenClient() client.async_config.enable_event_stream = True client._async_execution_manager = DummyManager() client._current_workflow_context = DummyContext({"X-Workflow-ID": "wf-ctx"}) @@ -73,7 +73,7 @@ def test_maybe_update_event_stream_headers_uses_context_when_enabled(): def test_maybe_update_event_stream_headers_prefers_source_headers(): - client = BrainClient() + client = HaxenClient() client.async_config.enable_event_stream = True manager = DummyManager() client._async_execution_manager = manager @@ -92,7 +92,7 @@ def test_maybe_update_event_stream_headers_prefers_source_headers(): ], ) def test_maybe_update_event_stream_headers_without_manager(source_headers, expected): - client = BrainClient() + client = HaxenClient() client.async_config.enable_event_stream = True client._current_workflow_context = DummyContext({"X-Workflow-ID": "wf-ctx"}) diff --git a/sdk/python/tests/test_connection_manager.py b/sdk/python/tests/test_connection_manager.py index 90ae28ad..b158f644 100644 --- a/sdk/python/tests/test_connection_manager.py +++ b/sdk/python/tests/test_connection_manager.py @@ -1,5 +1,5 @@ import asyncio -from brain_sdk.connection_manager import ( +from haxen_sdk.connection_manager import ( ConnectionManager, ConnectionConfig, ConnectionState, @@ -11,7 +11,7 @@ async def register_agent_with_status(self, **kwargs): return False, None # simulate failure so start enters reconnection -class FakeBrainHandler: +class FakeHaxenHandler: async def send_enhanced_heartbeat(self): return True @@ -19,7 +19,7 @@ async def send_enhanced_heartbeat(self): class FakeAgent: def __init__(self): self.client = FakeClient() - self.brain_handler = FakeBrainHandler() + self.haxen_handler = FakeHaxenHandler() self.node_id = "n" self.reasoners = [] self.skills = [] diff --git a/sdk/python/tests/test_decorators.py b/sdk/python/tests/test_decorators.py index 1c1f499b..bcd3cdfc 100644 --- a/sdk/python/tests/test_decorators.py +++ b/sdk/python/tests/test_decorators.py @@ -2,9 +2,9 @@ import pytest -from brain_sdk.decorators import reasoner, _execute_with_tracking -from brain_sdk.execution_context import ExecutionContext -from brain_sdk.agent_registry import set_current_agent, clear_current_agent +from haxen_sdk.decorators import reasoner, _execute_with_tracking +from haxen_sdk.execution_context import ExecutionContext +from haxen_sdk.agent_registry import set_current_agent, clear_current_agent from tests.helpers import StubAgent @@ -48,9 +48,9 @@ async def record_start(agent, ctx, payload): async def record_complete(agent, ctx, result, duration_ms, payload): captured.setdefault("complete", []).append((ctx, result)) - monkeypatch.setattr("brain_sdk.decorators._send_workflow_start", record_start) + monkeypatch.setattr("haxen_sdk.decorators._send_workflow_start", record_start) monkeypatch.setattr( - "brain_sdk.decorators._send_workflow_completion", record_complete + "haxen_sdk.decorators._send_workflow_completion", record_complete ) agent = StubAgent() @@ -92,9 +92,9 @@ async def record_error(agent, ctx, message, duration_ms, payload): calls.setdefault("error", []).append((ctx, message)) monkeypatch.setattr( - "brain_sdk.decorators._send_workflow_start", lambda *a, **k: asyncio.sleep(0) + "haxen_sdk.decorators._send_workflow_start", lambda *a, **k: asyncio.sleep(0) ) - monkeypatch.setattr("brain_sdk.decorators._send_workflow_error", record_error) + monkeypatch.setattr("haxen_sdk.decorators._send_workflow_error", record_error) agent = StubAgent() set_current_agent(agent) diff --git a/sdk/python/tests/test_did_manager.py b/sdk/python/tests/test_did_manager.py index aa7f04d6..415aa0fb 100644 --- a/sdk/python/tests/test_did_manager.py +++ b/sdk/python/tests/test_did_manager.py @@ -1,6 +1,6 @@ import datetime -from brain_sdk.did_manager import DIDManager, DIDIdentityPackage +from haxen_sdk.did_manager import DIDManager, DIDIdentityPackage def make_package(): @@ -30,12 +30,12 @@ def make_package(): "component_type": "skill", } }, - "brain_server_id": "brain-1", + "haxen_server_id": "haxen-1", } def test_register_agent_success(monkeypatch): - manager = DIDManager("http://brain", "node") + manager = DIDManager("http://haxen", "node") class DummyResponse: status_code = 200 @@ -55,7 +55,7 @@ def json(): def test_register_agent_failure_status(monkeypatch): - manager = DIDManager("http://brain", "node") + manager = DIDManager("http://haxen", "node") class DummyResponse: status_code = 500 @@ -68,7 +68,7 @@ class DummyResponse: def test_create_execution_context(monkeypatch): - manager = DIDManager("http://brain", "node") + manager = DIDManager("http://haxen", "node") package = manager._parse_identity_package(make_package()) assert isinstance(package, DIDIdentityPackage) manager.identity_package = package @@ -88,11 +88,11 @@ def test_create_execution_context(monkeypatch): def test_create_execution_context_missing_identity(): - manager = DIDManager("http://brain", "node") + manager = DIDManager("http://haxen", "node") assert manager.create_execution_context("e", "w", "s", "a", "b") is None def test_get_identity_summary_disabled(): - manager = DIDManager("http://brain", "node") + manager = DIDManager("http://haxen", "node") summary = manager.get_identity_summary() assert summary["enabled"] is False diff --git a/sdk/python/tests/test_dynamic_skills.py b/sdk/python/tests/test_dynamic_skills.py index 03f97bd9..a35907d6 100644 --- a/sdk/python/tests/test_dynamic_skills.py +++ b/sdk/python/tests/test_dynamic_skills.py @@ -4,7 +4,7 @@ import pytest from fastapi import FastAPI -from brain_sdk.dynamic_skills import DynamicMCPSkillManager +from haxen_sdk.dynamic_skills import DynamicMCPSkillManager class StubMCPClient: diff --git a/sdk/python/tests/test_execution_context_core.py b/sdk/python/tests/test_execution_context_core.py index f87a6426..5e58fd2f 100644 --- a/sdk/python/tests/test_execution_context_core.py +++ b/sdk/python/tests/test_execution_context_core.py @@ -1,6 +1,6 @@ import pytest -from brain_sdk.execution_context import ( +from haxen_sdk.execution_context import ( ExecutionContext, generate_execution_id, ) diff --git a/sdk/python/tests/test_execution_state.py b/sdk/python/tests/test_execution_state.py index 0b37d92f..d97e8cf3 100644 --- a/sdk/python/tests/test_execution_state.py +++ b/sdk/python/tests/test_execution_state.py @@ -1,5 +1,5 @@ import time -from brain_sdk.execution_state import ( +from haxen_sdk.execution_state import ( ExecutionBatch, ExecutionState, ExecutionStatus, diff --git a/sdk/python/tests/test_memory_client_core.py b/sdk/python/tests/test_memory_client_core.py index 49261a71..030e3bbf 100644 --- a/sdk/python/tests/test_memory_client_core.py +++ b/sdk/python/tests/test_memory_client_core.py @@ -8,7 +8,7 @@ import pytest import requests -from brain_sdk.memory import ( +from haxen_sdk.memory import ( GlobalMemoryClient, MemoryClient, MemoryInterface, @@ -31,14 +31,14 @@ def raise_for_status(self): @pytest.fixture(autouse=True) def mute_debug_logs(monkeypatch): - monkeypatch.setattr("brain_sdk.logger.log_debug", lambda *args, **kwargs: None) + monkeypatch.setattr("haxen_sdk.logger.log_debug", lambda *args, **kwargs: None) @pytest.fixture def memory_client(dummy_headers): context = SimpleNamespace(to_headers=lambda: dict(dummy_headers)) - brain_client = SimpleNamespace(api_base="http://brain.local/api/v1") - return MemoryClient(brain_client, context) + haxen_client = SimpleNamespace(api_base="http://haxen.local/api/v1") + return MemoryClient(haxen_client, context) @pytest.mark.unit @@ -275,11 +275,11 @@ def raise_for_status(self): return OkResponse() context = SimpleNamespace(to_headers=lambda: dict(dummy_headers)) - brain_client = SimpleNamespace( - api_base="http://brain.local/api/v1", + haxen_client = SimpleNamespace( + api_base="http://haxen.local/api/v1", _async_request=fake_async_request, ) - client = MemoryClient(brain_client, context) + client = MemoryClient(haxen_client, context) await client.set("key", {"value": 1}) diff --git a/sdk/python/tests/test_memory_events.py b/sdk/python/tests/test_memory_events.py index 2fa31d8e..3770c4be 100644 --- a/sdk/python/tests/test_memory_events.py +++ b/sdk/python/tests/test_memory_events.py @@ -6,8 +6,8 @@ import pytest -from brain_sdk.memory_events import PatternMatcher, EventSubscription, MemoryEventClient -from brain_sdk.types import MemoryChangeEvent +from haxen_sdk.memory_events import PatternMatcher, EventSubscription, MemoryEventClient +from haxen_sdk.types import MemoryChangeEvent def test_pattern_matcher_wildcards(): @@ -35,7 +35,7 @@ def test_event_subscription_matches_scoped_event(): def test_memory_event_client_subscription_and_unsubscribe(monkeypatch): ctx = SimpleNamespace(to_headers=lambda: {"Authorization": "token"}) - client = MemoryEventClient("http://brain", ctx) + client = MemoryEventClient("http://haxen", ctx) callback_called = asyncio.Event() @@ -55,7 +55,7 @@ async def callback(event): @pytest.mark.asyncio async def test_memory_event_client_history(monkeypatch): ctx = SimpleNamespace(to_headers=lambda: {"Authorization": "token"}) - client = MemoryEventClient("http://brain", ctx) + client = MemoryEventClient("http://haxen", ctx) class DummyResponse: def __init__(self): @@ -97,7 +97,7 @@ async def get(self, url, params=None, headers=None, timeout=None): @pytest.mark.asyncio async def test_memory_event_client_connect_builds_ws_url(monkeypatch): ctx = SimpleNamespace(to_headers=lambda: {"Authorization": "token"}) - client = MemoryEventClient("http://brain", ctx) + client = MemoryEventClient("http://haxen", ctx) record = {} listener_called = {} @@ -114,7 +114,7 @@ async def fake_connect(url, additional_headers=None): async def fake_listen(self): listener_called["run"] = True - monkeypatch.setattr("brain_sdk.memory_events.websockets.connect", fake_connect) + monkeypatch.setattr("haxen_sdk.memory_events.websockets.connect", fake_connect) monkeypatch.setattr(MemoryEventClient, "_listen", fake_listen, raising=False) await client.connect( @@ -122,7 +122,7 @@ async def fake_listen(self): ) await asyncio.sleep(0) - assert record["url"].startswith("ws://brain") + assert record["url"].startswith("ws://haxen") assert "patterns=cart.*,order.*" in record["url"] assert "scope=session" in record["url"] assert "scope_id=abc" in record["url"] @@ -133,7 +133,7 @@ async def fake_listen(self): @pytest.mark.asyncio async def test_memory_event_client_listen_dispatches(monkeypatch): ctx = SimpleNamespace(to_headers=lambda: {}) - client = MemoryEventClient("http://brain", ctx) + client = MemoryEventClient("http://haxen", ctx) received = [] @@ -189,7 +189,7 @@ def capture_task(coro): @pytest.mark.asyncio async def test_memory_event_client_handle_reconnect(monkeypatch): ctx = SimpleNamespace(to_headers=lambda: {}) - client = MemoryEventClient("http://brain", ctx) + client = MemoryEventClient("http://haxen", ctx) client._max_reconnect_attempts = 2 sleeps = [] @@ -217,7 +217,7 @@ async def fake_connect(*args, **kwargs): def test_on_change_decorator_marks_wrapper(): ctx = SimpleNamespace(to_headers=lambda: {}) - client = MemoryEventClient("http://brain", ctx) + client = MemoryEventClient("http://haxen", ctx) client.websocket = SimpleNamespace(open=True) @client.on_change("foo.*") diff --git a/sdk/python/tests/test_memory_flow_core.py b/sdk/python/tests/test_memory_flow_core.py index 717e9624..aff4e64d 100644 --- a/sdk/python/tests/test_memory_flow_core.py +++ b/sdk/python/tests/test_memory_flow_core.py @@ -5,7 +5,7 @@ import pytest import requests -from brain_sdk.memory import ( +from haxen_sdk.memory import ( GlobalMemoryClient, MemoryClient, MemoryInterface, @@ -88,11 +88,11 @@ async def get(self, url, params=None, headers=None, timeout=None): # type: igno monkeypatch.setattr(requests, "post", fake_post) monkeypatch.setattr(httpx, "AsyncClient", lambda *args, **kwargs: AsyncClientStub()) - monkeypatch.setattr("brain_sdk.logger.log_debug", lambda *args, **kwargs: None) + monkeypatch.setattr("haxen_sdk.logger.log_debug", lambda *args, **kwargs: None) context = SimpleNamespace(to_headers=lambda: dict(dummy_headers)) - brain_client = SimpleNamespace(api_base="http://brain.local/api/v1") - memory_client = MemoryClient(brain_client, context) + haxen_client = SimpleNamespace(api_base="http://haxen.local/api/v1") + memory_client = MemoryClient(haxen_client, context) interface = MemoryInterface(memory_client, SimpleNamespace()) # type: ignore[arg-type] # Default scope round-trip @@ -116,11 +116,11 @@ async def get(self, url, params=None, headers=None, timeout=None): # type: igno @pytest.mark.functional @pytest.mark.asyncio -async def test_memory_client_uses_brain_async_request(dummy_headers): +async def test_memory_client_uses_haxen_async_request(dummy_headers): calls: list[tuple[str, str, dict]] = [] - class DummyBrainClient: - api_base = "http://brain.local/api/v1" + class DummyHaxenClient: + api_base = "http://haxen.local/api/v1" async def _async_request(self, method, url, **kwargs): calls.append((method, url, kwargs)) @@ -129,7 +129,7 @@ async def _async_request(self, method, url, **kwargs): return DummyAsyncResponse(200, {"ok": True}) context = SimpleNamespace(to_headers=lambda: dict(dummy_headers)) - memory_client = MemoryClient(DummyBrainClient(), context) + memory_client = MemoryClient(DummyHaxenClient(), context) await memory_client.set("answer", 42) value = await memory_client.get("answer") diff --git a/sdk/python/tests/test_multimodal.py b/sdk/python/tests/test_multimodal.py index f3c64a4d..27142b75 100644 --- a/sdk/python/tests/test_multimodal.py +++ b/sdk/python/tests/test_multimodal.py @@ -1,4 +1,4 @@ -from brain_sdk.multimodal import image_from_file, audio_from_file, file_from_path +from haxen_sdk.multimodal import image_from_file, audio_from_file, file_from_path def test_image_from_file_and_audio_from_file(tmp_path): diff --git a/sdk/python/tests/test_multimodal_response.py b/sdk/python/tests/test_multimodal_response.py index 77f4c98c..32758352 100644 --- a/sdk/python/tests/test_multimodal_response.py +++ b/sdk/python/tests/test_multimodal_response.py @@ -1,5 +1,5 @@ import base64 -from brain_sdk.multimodal_response import AudioOutput, ImageOutput, FileOutput +from haxen_sdk.multimodal_response import AudioOutput, ImageOutput, FileOutput def test_audio_output_save_and_get_bytes(tmp_path): diff --git a/sdk/python/tests/test_pydantic_utils.py b/sdk/python/tests/test_pydantic_utils.py index 5c4e669f..815c5ea5 100644 --- a/sdk/python/tests/test_pydantic_utils.py +++ b/sdk/python/tests/test_pydantic_utils.py @@ -1,5 +1,5 @@ from pydantic import BaseModel -from brain_sdk.pydantic_utils import ( +from haxen_sdk.pydantic_utils import ( is_pydantic_model, is_optional_type, get_optional_inner_type, diff --git a/sdk/python/tests/test_rate_limiter_core.py b/sdk/python/tests/test_rate_limiter_core.py index 40d3561c..0490e13c 100644 --- a/sdk/python/tests/test_rate_limiter_core.py +++ b/sdk/python/tests/test_rate_limiter_core.py @@ -4,7 +4,7 @@ import pytest -from brain_sdk.rate_limiter import RateLimitError, StatelessRateLimiter +from haxen_sdk.rate_limiter import RateLimitError, StatelessRateLimiter class DummyHTTPError(Exception): @@ -49,7 +49,7 @@ async def test_execute_with_retry_eventual_success(monkeypatch): async def fake_sleep(delay): attempts["sleeps"].append(delay) - monkeypatch.setattr("brain_sdk.rate_limiter.asyncio.sleep", fake_sleep) + monkeypatch.setattr("haxen_sdk.rate_limiter.asyncio.sleep", fake_sleep) async def flaky_call(): attempts["count"] += 1 @@ -73,7 +73,7 @@ async def test_execute_with_retry_gives_up(monkeypatch): async def fake_sleep(delay): pass - monkeypatch.setattr("brain_sdk.rate_limiter.asyncio.sleep", fake_sleep) + monkeypatch.setattr("haxen_sdk.rate_limiter.asyncio.sleep", fake_sleep) async def always_fail(): raise DummyHTTPError() @@ -168,7 +168,7 @@ async def test_circuit_breaker_blocks_and_recovers(monkeypatch): async def fake_sleep(delay): return None - monkeypatch.setattr("brain_sdk.rate_limiter.asyncio.sleep", fake_sleep) + monkeypatch.setattr("haxen_sdk.rate_limiter.asyncio.sleep", fake_sleep) class Clock: def __init__(self, value: float): @@ -181,7 +181,7 @@ def advance(self, seconds: float) -> None: self.value += seconds clock = Clock(100.0) - monkeypatch.setattr("brain_sdk.rate_limiter.time.time", clock.time) + monkeypatch.setattr("haxen_sdk.rate_limiter.time.time", clock.time) async def always_limit(): raise DummyHTTPError() diff --git a/sdk/python/tests/test_result_cache.py b/sdk/python/tests/test_result_cache.py index 37f29683..d2cf6139 100644 --- a/sdk/python/tests/test_result_cache.py +++ b/sdk/python/tests/test_result_cache.py @@ -1,6 +1,6 @@ import time -from brain_sdk.result_cache import ResultCache -from brain_sdk.async_config import AsyncConfig +from haxen_sdk.result_cache import ResultCache +from haxen_sdk.async_config import AsyncConfig import asyncio diff --git a/sdk/python/tests/test_router.py b/sdk/python/tests/test_router.py index a99f9ab8..d5cb0b49 100644 --- a/sdk/python/tests/test_router.py +++ b/sdk/python/tests/test_router.py @@ -1,6 +1,6 @@ import pytest -from brain_sdk.router import AgentRouter +from haxen_sdk.router import AgentRouter class DummyAgent: diff --git a/sdk/python/tests/test_status_utils.py b/sdk/python/tests/test_status_utils.py index e3cc2470..ce14850d 100644 --- a/sdk/python/tests/test_status_utils.py +++ b/sdk/python/tests/test_status_utils.py @@ -1,4 +1,4 @@ -from brain_sdk.status import normalize_status, is_terminal, TERMINAL_STATUSES +from haxen_sdk.status import normalize_status, is_terminal, TERMINAL_STATUSES def test_status_normalization_all_values(): diff --git a/sdk/python/tests/test_types.py b/sdk/python/tests/test_types.py index 5f5c7543..a690940b 100644 --- a/sdk/python/tests/test_types.py +++ b/sdk/python/tests/test_types.py @@ -1,4 +1,4 @@ -from brain_sdk.types import ( +from haxen_sdk.types import ( ExecutionHeaders, AgentStatus, HeartbeatData, diff --git a/sdk/python/tests/test_utils.py b/sdk/python/tests/test_utils.py index b37be2e2..7b0c133d 100644 --- a/sdk/python/tests/test_utils.py +++ b/sdk/python/tests/test_utils.py @@ -1,7 +1,7 @@ import socket import pytest -from brain_sdk.utils import get_free_port +from haxen_sdk.utils import get_free_port def test_get_free_port_iterates_until_success(monkeypatch): diff --git a/sdk/python/tests/test_vc_generator.py b/sdk/python/tests/test_vc_generator.py index 7eb46376..2ab99031 100644 --- a/sdk/python/tests/test_vc_generator.py +++ b/sdk/python/tests/test_vc_generator.py @@ -2,7 +2,7 @@ from datetime import datetime from types import SimpleNamespace -from brain_sdk.vc_generator import VCGenerator +from haxen_sdk.vc_generator import VCGenerator def make_execution_context(): @@ -18,7 +18,7 @@ def make_execution_context(): def test_generate_execution_vc_success(monkeypatch): - generator = VCGenerator("http://brain") + generator = VCGenerator("http://haxen") generator.set_enabled(True) payload = { @@ -41,7 +41,7 @@ def fake_post(url, json=None, timeout=None): assert url.endswith("/execution/vc") return SimpleNamespace(status_code=200, json=lambda: payload) - monkeypatch.setattr("brain_sdk.vc_generator.requests.post", fake_post) + monkeypatch.setattr("haxen_sdk.vc_generator.requests.post", fake_post) vc = generator.generate_execution_vc( make_execution_context(), {"x": 1}, {"y": 2}, status="succeeded" @@ -50,7 +50,7 @@ def fake_post(url, json=None, timeout=None): def test_generate_execution_vc_disabled(): - generator = VCGenerator("http://brain") + generator = VCGenerator("http://haxen") generator.set_enabled(False) assert ( generator.generate_execution_vc( @@ -61,18 +61,18 @@ def test_generate_execution_vc_disabled(): def test_verify_vc(monkeypatch): - generator = VCGenerator("http://brain") + generator = VCGenerator("http://haxen") def fake_post(url, json=None, timeout=None): return SimpleNamespace(status_code=200, json=lambda: {"valid": True}) - monkeypatch.setattr("brain_sdk.vc_generator.requests.post", fake_post) + monkeypatch.setattr("haxen_sdk.vc_generator.requests.post", fake_post) result = generator.verify_vc({"proof": {}}) assert result == {"valid": True} def test_create_workflow_vc(monkeypatch): - generator = VCGenerator("http://brain") + generator = VCGenerator("http://haxen") payload = { "workflow_id": "wf-1", "session_id": "sess-1", @@ -88,24 +88,24 @@ def test_create_workflow_vc(monkeypatch): def fake_post(url, json=None, timeout=None): return SimpleNamespace(status_code=200, json=lambda: payload) - monkeypatch.setattr("brain_sdk.vc_generator.requests.post", fake_post) + monkeypatch.setattr("haxen_sdk.vc_generator.requests.post", fake_post) vc = generator.create_workflow_vc("wf-1", "sess-1", ["vc-1"]) assert vc.workflow_vc_id == "wvc-1" def test_get_workflow_vc_chain(monkeypatch): - generator = VCGenerator("http://brain") + generator = VCGenerator("http://haxen") def fake_get(url, timeout=None): return SimpleNamespace(status_code=200, json=lambda: {"chain": ["vc-1"]}) - monkeypatch.setattr("brain_sdk.vc_generator.requests.get", fake_get) + monkeypatch.setattr("haxen_sdk.vc_generator.requests.get", fake_get) chain = generator.get_workflow_vc_chain("wf-1") assert chain == {"chain": ["vc-1"]} def test_serialize_data_for_json_base64(): - generator = VCGenerator("http://brain") + generator = VCGenerator("http://haxen") generator.set_enabled(True) encoded = generator._serialize_data_for_json({"a": 1}) decoded = base64.b64decode(encoded.encode()).decode()