# Integration Guide\n\nThis document explains how the new project structure integrates with existing systems, API compatibility and versioning, database migration\nstrategies, deployment considerations, and monitoring and observability.\n\n## Table of Contents\n\n1. [Overview](#overview)\n2. [Existing System Integration](#existing-system-integration)\n3. [API Compatibility and Versioning](#api-compatibility-and-versioning)\n4. [Database Migration Strategies](#database-migration-strategies)\n5. [Deployment Considerations](#deployment-considerations)\n6. [Monitoring and Observability](#monitoring-and-observability)\n7. [Legacy System Bridge](#legacy-system-bridge)\n8. [Migration Pathways](#migration-pathways)\n9. [Troubleshooting Integration Issues](#troubleshooting-integration-issues)\n\n## Overview\n\nProvisioning has been designed with integration as a core principle, ensuring seamless compatibility between new development-focused components and\nexisting production systems while providing clear migration pathways.\n\n**Integration Principles**:\n\n- **Backward Compatibility**: All existing APIs and interfaces remain functional\n- **Gradual Migration**: Systems can be migrated incrementally without disruption\n- **Dual Operation**: New and legacy systems operate side-by-side during transition\n- **Zero Downtime**: Migrations occur without service interruption\n- **Data Integrity**: All data migrations are atomic and reversible\n\n**Integration Architecture**:\n\n```\nIntegration Ecosystem\n┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐\n│   Legacy Core   │ ←→ │  Bridge Layer   │ ←→ │   New Systems   │\n│                 │    │                 │    │                 │\n│ - ENV config    │    │ - Compatibility │    │ - TOML config   │\n│ - Direct calls  │    │ - Translation   │    │ - Orchestrator  │\n│ - File-based    │    │ - Monitoring    │    │ - Workflows     │\n│ - Simple logging│    │ - Validation    │    │ - REST APIs     │\n└─────────────────┘    └─────────────────┘    └─────────────────┘\n```\n\n## Existing System Integration\n\n### Command-Line Interface Integration\n\n**Seamless CLI Compatibility**:\n\n```\n# All existing commands continue to work unchanged\n./core/nulib/provisioning server create web-01 2xCPU-4 GB\n./core/nulib/provisioning taskserv install kubernetes\n./core/nulib/provisioning cluster create buildkit\n\n# New commands available alongside existing ones\n./src/core/nulib/provisioning server create web-01 2xCPU-4 GB --orchestrated\nnu workspace/tools/workspace.nu health --detailed\n```\n\n**Path Resolution Integration**:\n\n```\n# Automatic path resolution between systems\nuse workspace/lib/path-resolver.nu\n\n# Resolves to workspace path if available, falls back to core\nlet config_path = (path-resolver resolve_path "config" "user" --fallback-to-core)\n\n# Seamless extension discovery\nlet provider_path = (path-resolver resolve_extension "providers" "upcloud")\n```\n\n### Configuration System Bridge\n\n**Dual Configuration Support**:\n\n```\n# Configuration bridge supports both ENV and TOML\ndef get-config-value-bridge [key: string, default: string = ""] -> string {\n    # Try new TOML configuration first\n    let toml_value = try {\n        get-config-value $key\n    } catch { null }\n\n    if $toml_value != null {\n        return $toml_value\n    }\n\n    # Fall back to ENV variable (legacy support)\n    let env_key = ($key | str replace "." "_" | str upcase | $"PROVISIONING_($in)")\n    let env_value = ($env | get $env_key | default null)\n\n    if $env_value != null {\n        return $env_value\n    }\n\n    # Use default if provided\n    if $default != "" {\n        return $default\n    }\n\n    # Error with helpful migration message\n    error make {\n        msg: $"Configuration not found: ($key)",\n        help: $"Migrate from ($env_key) environment variable to ($key) in config file"\n    }\n}\n```\n\n### Data Integration\n\n**Shared Data Access**:\n\n```\n# Unified data access across old and new systems\ndef get-server-info [server_name: string] -> record {\n    # Try new orchestrator data store first\n    let orchestrator_data = try {\n        get-orchestrator-server-data $server_name\n    } catch { null }\n\n    if $orchestrator_data != null {\n        return $orchestrator_data\n    }\n\n    # Fall back to legacy file-based storage\n    let legacy_data = try {\n        get-legacy-server-data $server_name\n    } catch { null }\n\n    if $legacy_data != null {\n        return ($legacy_data | migrate-to-new-format)\n    }\n\n    error make {msg: $"Server not found: ($server_name)"}\n}\n```\n\n### Process Integration\n\n**Hybrid Process Management**:\n\n```\n# Orchestrator-aware process management\ndef create-server-integrated [\n    name: string,\n    plan: string,\n    --orchestrated: bool = false\n] -> record {\n    if $orchestrated and (check-orchestrator-available) {\n        # Use new orchestrator workflow\n        return (create-server-workflow $name $plan)\n    } else {\n        # Use legacy direct creation\n        return (create-server-direct $name $plan)\n    }\n}\n\ndef check-orchestrator-available [] -> bool {\n    try {\n        http get "http://localhost:9090/health" | get status == "ok"\n    } catch {\n        false\n    }\n}\n```\n\n## API Compatibility and Versioning\n\n### REST API Versioning\n\n**API Version Strategy**:\n\n- **v1**: Legacy compatibility API (existing functionality)\n- **v2**: Enhanced API with orchestrator features\n- **v3**: Full workflow and batch operation support\n\n**Version Header Support**:\n\n```\n# API calls with version specification\ncurl -H "API-Version: v1" http://localhost:9090/servers\ncurl -H "API-Version: v2" http://localhost:9090/workflows/servers/create\ncurl -H "API-Version: v3" http://localhost:9090/workflows/batch/submit\n```\n\n### API Compatibility Layer\n\n**Backward Compatible Endpoints**:\n\n```\n// Rust API compatibility layer\n#[derive(Debug, Serialize, Deserialize)]\nstruct ApiRequest {\n    version: Option<String>,\n    #[serde(flatten)]\n    payload: serde_json::Value,\n}\n\nasync fn handle_versioned_request(\n    headers: HeaderMap,\n    req: ApiRequest,\n) -> Result<ApiResponse, ApiError> {\n    let api_version = headers\n        .get("API-Version")\n        .and_then(|v| v.to_str().ok())\n        .unwrap_or("v1");\n\n    match api_version {\n        "v1" => handle_v1_request(req.payload).await,\n        "v2" => handle_v2_request(req.payload).await,\n        "v3" => handle_v3_request(req.payload).await,\n        _ => Err(ApiError::UnsupportedVersion(api_version.to_string())),\n    }\n}\n\n// V1 compatibility endpoint\nasync fn handle_v1_request(payload: serde_json::Value) -> Result<ApiResponse, ApiError> {\n    // Transform request to legacy format\n    let legacy_request = transform_to_legacy_format(payload)?;\n\n    // Execute using legacy system\n    let result = execute_legacy_operation(legacy_request).await?;\n\n    // Transform response to v1 format\n    Ok(transform_to_v1_response(result))\n}\n```\n\n### Schema Evolution\n\n**Backward Compatible Schema Changes**:\n\n```\n# API schema with version support\nlet ServerCreateRequest = {\n    # V1 fields (always supported)\n    name | string,\n    plan | string,\n    zone | string | default = "auto",\n\n    # V2 additions (optional for backward compatibility)\n    orchestrated | bool | default = false,\n    workflow_options | { } | optional,\n\n    # V3 additions\n    batch_options | { } | optional,\n    dependencies | array | default = [],\n\n    # Version constraints\n    api_version | string | default = "v1",\n} in\nServerCreateRequest\n\n# Conditional validation based on API version\nlet WorkflowOptions = {\n    wait_for_completion | bool | default = true,\n    timeout_seconds | number | default = 300,\n    retry_count | number | default = 3,\n} in\nWorkflowOptions\n```\n\n### Client SDK Compatibility\n\n**Multi-Version Client Support**:\n\n```\n# Nushell client with version support\ndef "client create-server" [\n    name: string,\n    plan: string,\n    --api-version: string = "v1",\n    --orchestrated: bool = false\n] -> record {\n    let endpoint = match $api_version {\n        "v1" => "/servers",\n        "v2" => "/workflows/servers/create",\n        "v3" => "/workflows/batch/submit",\n        _ => (error make {msg: $"Unsupported API version: ($api_version)"})\n    }\n\n    let request_body = match $api_version {\n        "v1" => {name: $name, plan: $plan},\n        "v2" => {name: $name, plan: $plan, orchestrated: $orchestrated},\n        "v3" => {\n            operations: [{\n                id: "create_server",\n                type: "server_create",\n                config: {name: $name, plan: $plan}\n            }]\n        },\n        _ => (error make {msg: $"Unsupported API version: ($api_version)"})\n    }\n\n    http post $"http://localhost:9090($endpoint)" $request_body\n        --headers {\n            "Content-Type": "application/json",\n            "API-Version": $api_version\n        }\n}\n```\n\n## Database Migration Strategies\n\n### Database Architecture Evolution\n\n**Migration Strategy**:\n\n```\nDatabase Evolution Path\n┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐\n│  File-based     │ → │   SQLite        │ → │   SurrealDB     │\n│  Storage        │    │   Migration     │    │   Full Schema   │\n│                 │    │                 │    │                 │\n│ - JSON files    │    │ - Structured    │    │ - Graph DB      │\n│ - Text logs     │    │ - Transactions  │    │ - Real-time     │\n│ - Simple state  │    │ - Backup/restore│    │ - Clustering    │\n└─────────────────┘    └─────────────────┘    └─────────────────┘\n```\n\n### Migration Scripts\n\n**Automated Database Migration**:\n\n```\n# Database migration orchestration\ndef migrate-database [\n    --from: string = "filesystem",\n    --to: string = "surrealdb",\n    --backup-first: bool = true,\n    --verify: bool = true\n] -> record {\n    if $backup_first {\n        print "Creating backup before migration..."\n        let backup_result = (create-database-backup $from)\n        print $"Backup created: ($backup_result.path)"\n    }\n\n    print $"Migrating from ($from) to ($to)..."\n\n    match [$from, $to] {\n        ["filesystem", "sqlite"] => migrate_filesystem_to_sqlite,\n        ["filesystem", "surrealdb"] => migrate_filesystem_to_surrealdb,\n        ["sqlite", "surrealdb"] => migrate_sqlite_to_surrealdb,\n        _ => (error make {msg: $"Unsupported migration path: ($from) → ($to)"})\n    }\n\n    if $verify {\n        print "Verifying migration integrity..."\n        let verification = (verify-migration $from $to)\n        if not $verification.success {\n            error make {\n                msg: $"Migration verification failed: ($verification.errors)",\n                help: "Restore from backup and retry migration"\n            }\n        }\n    }\n\n    print $"Migration from ($from) to ($to) completed successfully"\n    {from: $from, to: $to, status: "completed", migrated_at: (date now)}\n}\n```\n\n**File System to SurrealDB Migration**:\n\n```\ndef migrate_filesystem_to_surrealdb [] -> record {\n    # Initialize SurrealDB connection\n    let db = (connect-surrealdb)\n\n    # Migrate server data\n    let server_files = (ls data/servers/*.json)\n    let migrated_servers = []\n\n    for server_file in $server_files {\n        let server_data = (open $server_file.name | from json)\n\n        # Transform to new schema\n        let server_record = {\n            id: $server_data.id,\n            name: $server_data.name,\n            plan: $server_data.plan,\n            zone: ($server_data.zone? | default "unknown"),\n            status: $server_data.status,\n            ip_address: $server_data.ip_address?,\n            created_at: $server_data.created_at,\n            updated_at: (date now),\n            metadata: ($server_data.metadata? | default {}),\n            tags: ($server_data.tags? | default [])\n        }\n\n        # Insert into SurrealDB\n        let insert_result = try {\n            query-surrealdb $"CREATE servers:($server_record.id) CONTENT ($server_record | to json)"\n        } catch { |e|\n            print $"Warning: Failed to migrate server ($server_data.name): ($e.msg)"\n        }\n\n        $migrated_servers = ($migrated_servers | append $server_record.id)\n    }\n\n    # Migrate workflow data\n    migrate_workflows_to_surrealdb $db\n\n    # Migrate state data\n    migrate_state_to_surrealdb $db\n\n    {\n        migrated_servers: ($migrated_servers | length),\n        migrated_workflows: (migrate_workflows_to_surrealdb $db).count,\n        status: "completed"\n    }\n}\n```\n\n### Data Integrity Verification\n\n**Migration Verification**:\n\n```\ndef verify-migration [from: string, to: string] -> record {\n    print "Verifying data integrity..."\n\n    let source_data = (read-source-data $from)\n    let target_data = (read-target-data $to)\n\n    let errors = []\n\n    # Verify record counts\n    if $source_data.servers.count != $target_data.servers.count {\n        $errors = ($errors | append "Server count mismatch")\n    }\n\n    # Verify key records\n    for server in $source_data.servers {\n        let target_server = ($target_data.servers | where id == $server.id | first)\n\n        if ($target_server | is-empty) {\n            $errors = ($errors | append $"Missing server: ($server.id)")\n        } else {\n            # Verify critical fields\n            if $target_server.name != $server.name {\n                $errors = ($errors | append $"Name mismatch for server ($server.id)")\n            }\n\n            if $target_server.status != $server.status {\n                $errors = ($errors | append $"Status mismatch for server ($server.id)")\n            }\n        }\n    }\n\n    {\n        success: ($errors | length) == 0,\n        errors: $errors,\n        verified_at: (date now)\n    }\n}\n```\n\n## Deployment Considerations\n\n### Deployment Architecture\n\n**Hybrid Deployment Model**:\n\n```\nDeployment Architecture\n┌─────────────────────────────────────────────────────────────────┐\n│                    Load Balancer / Reverse Proxy               │\n└─────────────────────┬───────────────────────────────────────────┘\n                      │\n    ┌─────────────────┼─────────────────┐\n    │                 │                 │\n┌───▼────┐      ┌─────▼─────┐      ┌───▼────┐\n│Legacy  │      │Orchestrator│      │New     │\n│System  │ ←→   │Bridge      │  ←→  │Systems │\n│        │      │            │      │        │\n│- CLI   │      │- API Gate  │      │- REST  │\n│- Files │      │- Compat    │      │- DB    │\n│- Logs  │      │- Monitor   │      │- Queue │\n└────────┘      └────────────┘      └────────┘\n```\n\n### Deployment Strategies\n\n**Blue-Green Deployment**:\n\n```\n# Blue-Green deployment with integration bridge\n# Phase 1: Deploy new system alongside existing (Green environment)\ncd src/tools\nmake all\nmake create-installers\n\n# Install new system without disrupting existing\n./packages/installers/install-provisioning-2.0.0.sh \\n    --install-path /opt/provisioning-v2 \\n    --no-replace-existing \\n    --enable-bridge-mode\n\n# Phase 2: Start orchestrator and validate integration\n/opt/provisioning-v2/bin/orchestrator start --bridge-mode --legacy-path /opt/provisioning-v1\n\n# Phase 3: Gradual traffic shift\n# Route 10% traffic to new system\nnginx-traffic-split --new-backend 10%\n\n# Validate metrics and gradually increase\nnginx-traffic-split --new-backend 50%\nnginx-traffic-split --new-backend 90%\n\n# Phase 4: Complete cutover\nnginx-traffic-split --new-backend 100%\n/opt/provisioning-v1/bin/orchestrator stop\n```\n\n**Rolling Update**:\n\n```\ndef rolling-deployment [\n    --target-version: string,\n    --batch-size: int = 3,\n    --health-check-interval: duration = 30sec\n] -> record {\n    let nodes = (get-deployment-nodes)\n    let batches = ($nodes | group_by --chunk-size $batch_size)\n\n    let deployment_results = []\n\n    for batch in $batches {\n        print $"Deploying to batch: ($batch | get name | str join ', ')"\n\n        # Deploy to batch\n        for node in $batch {\n            deploy-to-node $node $target_version\n        }\n\n        # Wait for health checks\n        sleep $health_check_interval\n\n        # Verify batch health\n        let batch_health = ($batch | each { |node| check-node-health $node })\n        let healthy_nodes = ($batch_health | where healthy == true | length)\n\n        if $healthy_nodes != ($batch | length) {\n            # Rollback batch on failure\n            print $"Health check failed, rolling back batch"\n            for node in $batch {\n                rollback-node $node\n            }\n            error make {msg: "Rolling deployment failed at batch"}\n        }\n\n        print $"Batch deployed successfully"\n        $deployment_results = ($deployment_results | append {\n            batch: $batch,\n            status: "success",\n            deployed_at: (date now)\n        })\n    }\n\n    {\n        strategy: "rolling",\n        target_version: $target_version,\n        batches: ($deployment_results | length),\n        status: "completed",\n        completed_at: (date now)\n    }\n}\n```\n\n### Configuration Deployment\n\n**Environment-Specific Deployment**:\n\n```\n# Development deployment\nPROVISIONING_ENV=dev ./deploy.sh \\n    --config-source config.dev.toml \\n    --enable-debug \\n    --enable-hot-reload\n\n# Staging deployment\nPROVISIONING_ENV=staging ./deploy.sh \\n    --config-source config.staging.toml \\n    --enable-monitoring \\n    --backup-before-deploy\n\n# Production deployment\nPROVISIONING_ENV=prod ./deploy.sh \\n    --config-source config.prod.toml \\n    --zero-downtime \\n    --enable-all-monitoring \\n    --backup-before-deploy \\n    --health-check-timeout 5m\n```\n\n### Container Integration\n\n**Docker Deployment with Bridge**:\n\n```\n# Multi-stage Docker build supporting both systems\nFROM rust:1.70 as builder\nWORKDIR /app\nCOPY . .\nRUN cargo build --release\n\nFROM ubuntu:22.04 as runtime\nWORKDIR /app\n\n# Install both legacy and new systems\nCOPY --from=builder /app/target/release/orchestrator /app/bin/\nCOPY legacy-provisioning/ /app/legacy/\nCOPY config/ /app/config/\n\n# Bridge script for dual operation\nCOPY bridge-start.sh /app/bin/\n\nENV PROVISIONING_BRIDGE_MODE=true\nENV PROVISIONING_LEGACY_PATH=/app/legacy\nENV PROVISIONING_NEW_PATH=/app/bin\n\nEXPOSE 8080\nCMD ["/app/bin/bridge-start.sh"]\n```\n\n**Kubernetes Integration**:\n\n```\n# Kubernetes deployment with bridge sidecar\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: provisioning-system\nspec:\n  replicas: 3\n  template:\n    spec:\n      containers:\n      - name: orchestrator\n        image: provisioning-system:2.0.0\n        ports:\n        - containerPort: 8080\n        env:\n        - name: PROVISIONING_BRIDGE_MODE\n          value: "true"\n        volumeMounts:\n        - name: config\n          mountPath: /app/config\n        - name: legacy-data\n          mountPath: /app/legacy/data\n\n      - name: legacy-bridge\n        image: provisioning-legacy:1.0.0\n        env:\n        - name: BRIDGE_ORCHESTRATOR_URL\n          value: "http://localhost:9090"\n        volumeMounts:\n        - name: legacy-data\n          mountPath: /data\n\n      volumes:\n      - name: config\n        configMap:\n          name: provisioning-config\n      - name: legacy-data\n        persistentVolumeClaim:\n          claimName: provisioning-data\n```\n\n## Monitoring and Observability\n\n### Integrated Monitoring Architecture\n\n**Monitoring Stack Integration**:\n\n```\nObservability Architecture\n┌─────────────────────────────────────────────────────────────────┐\n│                    Monitoring Dashboard                         │\n│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐           │\n│  │   Grafana   │  │  Jaeger     │  │  AlertMgr   │           │\n│  └─────────────┘  └─────────────┘  └─────────────┘           │\n└─────────────┬───────────────┬───────────────┬─────────────────┘\n              │               │               │\n   ┌──────────▼──────────┐   │   ┌───────────▼───────────┐\n   │     Prometheus      │   │   │      Jaeger           │\n   │   (Metrics)         │   │   │    (Tracing)          │\n   └──────────┬──────────┘   │   └───────────┬───────────┘\n              │               │               │\n┌─────────────▼─────────────┐ │ ┌─────────────▼─────────────┐\n│        Legacy             │ │ │        New System         │\n│      Monitoring           │ │ │       Monitoring          │\n│                           │ │ │                           │\n│ - File-based logs        │ │ │ - Structured logs         │\n│ - Simple metrics         │ │ │ - Prometheus metrics      │\n│ - Basic health checks    │ │ │ - Distributed tracing     │\n└───────────────────────────┘ │ └───────────────────────────┘\n                              │\n                    ┌─────────▼─────────┐\n                    │   Bridge Monitor  │\n                    │                   │\n                    │ - Integration     │\n                    │ - Compatibility   │\n                    │ - Migration       │\n                    └───────────────────┘\n```\n\n### Metrics Integration\n\n**Unified Metrics Collection**:\n\n```\n# Metrics bridge for legacy and new systems\ndef collect-system-metrics [] -> record {\n    let legacy_metrics = collect-legacy-metrics\n    let new_metrics = collect-new-metrics\n    let bridge_metrics = collect-bridge-metrics\n\n    {\n        timestamp: (date now),\n        legacy: $legacy_metrics,\n        new: $new_metrics,\n        bridge: $bridge_metrics,\n        integration: {\n            compatibility_rate: (calculate-compatibility-rate $bridge_metrics),\n            migration_progress: (calculate-migration-progress),\n            system_health: (assess-overall-health $legacy_metrics $new_metrics)\n        }\n    }\n}\n\ndef collect-legacy-metrics [] -> record {\n    let log_files = (ls logs/*.log)\n    let process_stats = (get-process-stats "legacy-provisioning")\n\n    {\n        active_processes: $process_stats.count,\n        log_file_sizes: ($log_files | get size | math sum),\n        last_activity: (get-last-log-timestamp),\n        error_count: (count-log-errors "last 1h"),\n        performance: {\n            avg_response_time: (calculate-avg-response-time),\n            throughput: (calculate-throughput)\n        }\n    }\n}\n\ndef collect-new-metrics [] -> record {\n    let orchestrator_stats = try {\n        http get "http://localhost:9090/metrics"\n    } catch {\n        {status: "unavailable"}\n    }\n\n    {\n        orchestrator: $orchestrator_stats,\n        workflow_stats: (get-workflow-metrics),\n        api_stats: (get-api-metrics),\n        database_stats: (get-database-metrics)\n    }\n}\n```\n\n### Logging Integration\n\n**Unified Logging Strategy**:\n\n```\n# Structured logging bridge\ndef log-integrated [\n    level: string,\n    message: string,\n    --component: string = "bridge",\n    --legacy-compat: bool = true\n] {\n    let log_entry = {\n        timestamp: (date now | format date "%Y-%m-%d %H:%M:%S%.3f"),\n        level: $level,\n        component: $component,\n        message: $message,\n        system: "integrated",\n        correlation_id: (generate-correlation-id)\n    }\n\n    # Write to structured log (new system)\n    $log_entry | to json | save --append logs/integrated.jsonl\n\n    if $legacy_compat {\n        # Write to legacy log format\n        let legacy_entry = $"[($log_entry.timestamp)] [($level)] ($component): ($message)"\n        $legacy_entry | save --append logs/legacy.log\n    }\n\n    # Send to monitoring system\n    send-to-monitoring $log_entry\n}\n```\n\n### Health Check Integration\n\n**Comprehensive Health Monitoring**:\n\n```\ndef health-check-integrated [] -> record {\n    let health_checks = [\n        {name: "legacy-system", check: (check-legacy-health)},\n        {name: "orchestrator", check: (check-orchestrator-health)},\n        {name: "database", check: (check-database-health)},\n        {name: "bridge-compatibility", check: (check-bridge-health)},\n        {name: "configuration", check: (check-config-health)}\n    ]\n\n    let results = ($health_checks | each { |check|\n        let result = try {\n            do $check.check\n        } catch { |e|\n            {status: "unhealthy", error: $e.msg}\n        }\n\n        {name: $check.name, result: $result}\n    })\n\n    let healthy_count = ($results | where result.status == "healthy" | length)\n    let total_count = ($results | length)\n\n    {\n        overall_status: (if $healthy_count == $total_count { "healthy" } else { "degraded" }),\n        healthy_services: $healthy_count,\n        total_services: $total_count,\n        services: $results,\n        checked_at: (date now)\n    }\n}\n```\n\n## Legacy System Bridge\n\n### Bridge Architecture\n\n**Bridge Component Design**:\n\n```\n# Legacy system bridge module\nexport module bridge {\n    # Bridge state management\n    export def init-bridge [] -> record {\n        let bridge_config = get-config-section "bridge"\n\n        {\n            legacy_path: ($bridge_config.legacy_path? | default "/opt/provisioning-v1"),\n            new_path: ($bridge_config.new_path? | default "/opt/provisioning-v2"),\n            mode: ($bridge_config.mode? | default "compatibility"),\n            monitoring_enabled: ($bridge_config.monitoring? | default true),\n            initialized_at: (date now)\n        }\n    }\n\n    # Command translation layer\n    export def translate-command [\n        legacy_command: list<string>\n    ] -> list<string> {\n        match $legacy_command {\n            ["provisioning", "server", "create", $name, $plan, ...$args] => {\n                let new_args = ($args | each { |arg|\n                    match $arg {\n                        "--dry-run" => "--dry-run",\n                        "--wait" => "--wait",\n                        $zone if ($zone | str starts-with "--zone=") => $zone,\n                        _ => $arg\n                    }\n                })\n\n                ["provisioning", "server", "create", $name, $plan] ++ $new_args ++ ["--orchestrated"]\n            },\n            _ => $legacy_command  # Pass through unchanged\n        }\n    }\n\n    # Data format translation\n    export def translate-response [\n        legacy_response: record,\n        target_format: string = "v2"\n    ] -> record {\n        match $target_format {\n            "v2" => {\n                id: ($legacy_response.id? | default (generate-uuid)),\n                name: $legacy_response.name,\n                status: $legacy_response.status,\n                created_at: ($legacy_response.created_at? | default (date now)),\n                metadata: ($legacy_response | reject name status created_at),\n                version: "v2-compat"\n            },\n            _ => $legacy_response\n        }\n    }\n}\n```\n\n### Bridge Operation Modes\n\n**Compatibility Mode**:\n\n```\n# Full compatibility with legacy system\ndef run-compatibility-mode [] {\n    print "Starting bridge in compatibility mode..."\n\n    # Intercept legacy commands\n    let legacy_commands = monitor-legacy-commands\n\n    for command in $legacy_commands {\n        let translated = (bridge translate-command $command)\n\n        try {\n            let result = (execute-new-system $translated)\n            let legacy_result = (bridge translate-response $result "v1")\n            respond-to-legacy $legacy_result\n        } catch { |e|\n            # Fall back to legacy system on error\n            let fallback_result = (execute-legacy-system $command)\n            respond-to-legacy $fallback_result\n        }\n    }\n}\n```\n\n**Migration Mode**:\n\n```\n# Gradual migration with traffic splitting\ndef run-migration-mode [\n    --new-system-percentage: int = 50\n] {\n    print $"Starting bridge in migration mode (($new_system_percentage)% new system)"\n\n    let commands = monitor-all-commands\n\n    for command in $commands {\n        let route_to_new = ((random integer 1..100) <= $new_system_percentage)\n\n        if $route_to_new {\n            try {\n                execute-new-system $command\n            } catch {\n                # Fall back to legacy on failure\n                execute-legacy-system $command\n            }\n        } else {\n            execute-legacy-system $command\n        }\n    }\n}\n```\n\n## Migration Pathways\n\n### Migration Phases\n\n**Phase 1: Parallel Deployment**\n\n- Deploy new system alongside existing\n- Enable bridge for compatibility\n- Begin data synchronization\n- Monitor integration health\n\n**Phase 2: Gradual Migration**\n\n- Route increasing traffic to new system\n- Migrate data in background\n- Validate consistency\n- Address integration issues\n\n**Phase 3: Full Migration**\n\n- Complete traffic cutover\n- Decommission legacy system\n- Clean up bridge components\n- Finalize data migration\n\n### Migration Automation\n\n**Automated Migration Orchestration**:\n\n```\ndef execute-migration-plan [\n    migration_plan: string,\n    --dry-run: bool = false,\n    --skip-backup: bool = false\n] -> record {\n    let plan = (open $migration_plan | from yaml)\n\n    if not $skip_backup {\n        create-pre-migration-backup\n    }\n\n    let migration_results = []\n\n    for phase in $plan.phases {\n        print $"Executing migration phase: ($phase.name)"\n\n        if $dry_run {\n            print $"[DRY RUN] Would execute phase: ($phase)"\n            continue\n        }\n\n        let phase_result = try {\n            execute-migration-phase $phase\n        } catch { |e|\n            print $"Migration phase failed: ($e.msg)"\n\n            if $phase.rollback_on_failure? | default false {\n                print "Rolling back migration phase..."\n                rollback-migration-phase $phase\n            }\n\n            error make {msg: $"Migration failed at phase ($phase.name): ($e.msg)"}\n        }\n\n        $migration_results = ($migration_results | append $phase_result)\n\n        # Wait between phases if specified\n        if "wait_seconds" in $phase {\n            sleep ($phase.wait_seconds * 1sec)\n        }\n    }\n\n    {\n        migration_plan: $migration_plan,\n        phases_completed: ($migration_results | length),\n        status: "completed",\n        completed_at: (date now),\n        results: $migration_results\n    }\n}\n```\n\n**Migration Validation**:\n\n```\ndef validate-migration-readiness [] -> record {\n    let checks = [\n        {name: "backup-available", check: (check-backup-exists)},\n        {name: "new-system-healthy", check: (check-new-system-health)},\n        {name: "database-accessible", check: (check-database-connectivity)},\n        {name: "configuration-valid", check: (validate-migration-config)},\n        {name: "resources-available", check: (check-system-resources)},\n        {name: "network-connectivity", check: (check-network-health)}\n    ]\n\n    let results = ($checks | each { |check|\n        {\n            name: $check.name,\n            result: (do $check.check),\n            timestamp: (date now)\n        }\n    })\n\n    let failed_checks = ($results | where result.status != "ready")\n\n    {\n        ready_for_migration: ($failed_checks | length) == 0,\n        checks: $results,\n        failed_checks: $failed_checks,\n        validated_at: (date now)\n    }\n}\n```\n\n## Troubleshooting Integration Issues\n\n### Common Integration Problems\n\n#### API Compatibility Issues\n\n**Problem**: Version mismatch between client and server\n\n```\n# Diagnosis\ncurl -H "API-Version: v1" http://localhost:9090/health\ncurl -H "API-Version: v2" http://localhost:9090/health\n\n# Solution: Check supported versions\ncurl http://localhost:9090/api/versions\n\n# Update client API version\nexport PROVISIONING_API_VERSION=v2\n```\n\n#### Configuration Bridge Issues\n\n**Problem**: Configuration not found in either system\n\n```\n# Diagnosis\ndef diagnose-config-issue [key: string] -> record {\n    let toml_result = try {\n        get-config-value $key\n    } catch { |e| {status: "failed", error: $e.msg} }\n\n    let env_key = ($key | str replace "." "_" | str upcase | $"PROVISIONING_($in)")\n    let env_result = try {\n        $env | get $env_key\n    } catch { |e| {status: "failed", error: $e.msg} }\n\n    {\n        key: $key,\n        toml_config: $toml_result,\n        env_config: $env_result,\n        migration_needed: ($toml_result.status == "failed" and $env_result.status != "failed")\n    }\n}\n\n# Solution: Migrate configuration\ndef migrate-single-config [key: string] {\n    let diagnosis = (diagnose-config-issue $key)\n\n    if $diagnosis.migration_needed {\n        let env_value = $diagnosis.env_config\n        set-config-value $key $env_value\n        print $"Migrated ($key) from environment variable"\n    }\n}\n```\n\n#### Database Integration Issues\n\n**Problem**: Data inconsistency between systems\n\n```\n# Diagnosis and repair\ndef repair-data-consistency [] -> record {\n    let legacy_data = (read-legacy-data)\n    let new_data = (read-new-data)\n\n    let inconsistencies = []\n\n    # Check server records\n    for server in $legacy_data.servers {\n        let new_server = ($new_data.servers | where id == $server.id | first)\n\n        if ($new_server | is-empty) {\n            print $"Missing server in new system: ($server.id)"\n            create-server-record $server\n            $inconsistencies = ($inconsistencies | append {type: "missing", id: $server.id})\n        } else if $new_server != $server {\n            print $"Inconsistent server data: ($server.id)"\n            update-server-record $server\n            $inconsistencies = ($inconsistencies | append {type: "inconsistent", id: $server.id})\n        }\n    }\n\n    {\n        inconsistencies_found: ($inconsistencies | length),\n        repairs_applied: ($inconsistencies | length),\n        repaired_at: (date now)\n    }\n}\n```\n\n### Debug Tools\n\n**Integration Debug Mode**:\n\n```\n# Enable comprehensive debugging\nexport PROVISIONING_DEBUG=true\nexport PROVISIONING_LOG_LEVEL=debug\nexport PROVISIONING_BRIDGE_DEBUG=true\nexport PROVISIONING_INTEGRATION_TRACE=true\n\n# Run with integration debugging\nprovisioning server create test-server 2xCPU-4 GB --debug-integration\n```\n\n**Health Check Debugging**:\n\n```\ndef debug-integration-health [] -> record {\n    print "=== Integration Health Debug ==="\n\n    # Check all integration points\n    let legacy_health = try {\n        check-legacy-system\n    } catch { |e| {status: "error", error: $e.msg} }\n\n    let orchestrator_health = try {\n        http get "http://localhost:9090/health"\n    } catch { |e| {status: "error", error: $e.msg} }\n\n    let bridge_health = try {\n        check-bridge-status\n    } catch { |e| {status: "error", error: $e.msg} }\n\n    let config_health = try {\n        validate-config-integration\n    } catch { |e| {status: "error", error: $e.msg} }\n\n    print $"Legacy System: ($legacy_health.status)"\n    print $"Orchestrator: ($orchestrator_health.status)"\n    print $"Bridge: ($bridge_health.status)"\n    print $"Configuration: ($config_health.status)"\n\n    {\n        legacy: $legacy_health,\n        orchestrator: $orchestrator_health,\n        bridge: $bridge_health,\n        configuration: $config_health,\n        debug_timestamp: (date now)\n    }\n}\n```\n\nThis integration guide provides a comprehensive framework for seamlessly integrating new development components with existing production systems while\nmaintaining reliability, compatibility, and clear migration pathways.
