UNPKG

supa-seed

Version:

A constraint-aware, framework-agnostic database seeding framework with deep PostgreSQL business logic discovery and MakerKit integration support

762 lines โ€ข 37.2 kB
"use strict"; /** * Detection System Integration Layer for Epic 2: Smart Platform Detection Engine * Integrates new Architecture Detection Engine with existing schema introspection and framework detection * Part of Task 2.1.5: Integrate with existing schema introspection and framework detection */ Object.defineProperty(exports, "__esModule", { value: true }); exports.DEFAULT_UNIFIED_DETECTION_CONFIG = exports.DetectionIntegrationEngine = void 0; const logger_1 = require("../../core/utils/logger"); // Import caching system const detection_cache_1 = require("./detection-cache"); // Import auto-configuration system const auto_configurator_1 = require("./auto-configurator"); // Import existing detection systems const schema_introspector_1 = require("../../schema/schema-introspector"); const makerkit_detector_1 = require("../../features/integration/strategies/makerkit-detector"); // Import new architecture detection system const architecture_detector_1 = require("./architecture-detector"); const evidence_collector_1 = require("./evidence-collector"); // Import new domain detection system const domain_detector_1 = require("./domain-detector"); /** * Main integration orchestrator for all detection systems */ class DetectionIntegrationEngine { constructor(client, databaseUrl) { this.client = client; this.databaseUrl = databaseUrl || this.extractUrlFromClient(client); this.schemaIntrospector = new schema_introspector_1.SchemaIntrospector(client); this.makerKitDetector = new makerkit_detector_1.MakerKitDetector(client); this.architectureDetector = new architecture_detector_1.ArchitectureDetectionEngine(); this.domainDetector = new domain_detector_1.DomainDetectionEngine(); this.evidenceCollector = new evidence_collector_1.ArchitectureEvidenceCollector(); this.cacheManager = new detection_cache_1.DetectionCacheManager(); this.autoConfigurator = new auto_configurator_1.AutoConfigurator(); } /** * Perform unified detection with auto-configuration */ async performUnifiedDetectionWithAutoConfig(autoConfigOptions = {}, detectionConfig = {}) { const fullDetectionConfig = { enableCrossValidation: true, enableConflictResolution: true, maxExecutionTime: 30000, enableCaching: true, confidenceThreshold: 0.6, ...detectionConfig }; const startTime = Date.now(); logger_1.Logger.info('๐Ÿ”„ Starting unified detection with auto-configuration...'); // Check cache first if enabled let cacheKey; if (fullDetectionConfig.enableCaching) { try { // Generate schema hash for cache validation if (!this.schemaHash) { this.schemaHash = await detection_cache_1.DetectionCacheUtils.generateSchemaHash(this.client); } // Include auto-config options in cache key const cacheData = { detection: fullDetectionConfig, autoConfig: autoConfigOptions }; cacheKey = this.cacheManager.generateCacheKey(this.databaseUrl, this.schemaHash, cacheData); const cachedEntry = await this.cacheManager.retrieve(cacheKey, this.databaseUrl, this.schemaHash); if (cachedEntry && cachedEntry.autoConfiguration) { logger_1.Logger.info('๐Ÿ“ฆ Using cached unified detection and auto-configuration results'); logger_1.Logger.debug(`Cache hit with detection confidence: ${cachedEntry.detectionResults.integration.overallConfidence}`); logger_1.Logger.debug(`Cache hit with config confidence: ${cachedEntry.autoConfiguration.confidence}`); return { detection: cachedEntry.detectionResults, autoConfiguration: cachedEntry.autoConfiguration }; } } catch (error) { logger_1.Logger.debug('Cache lookup failed:', error.message); // Continue with fresh detection } } try { // Step 1: Perform unified detection const detectionResults = await this.performUnifiedDetection(fullDetectionConfig); // Step 2: Generate auto-configuration from detection results logger_1.Logger.debug('๐Ÿ”ง Generating auto-configuration from detection results...'); const autoConfigStartTime = Date.now(); const autoConfiguration = await this.autoConfigurator.generateConfiguration(detectionResults, autoConfigOptions); const autoConfigTime = Date.now() - autoConfigStartTime; logger_1.Logger.success(`โœ… Auto-configuration completed in ${autoConfigTime}ms with ${autoConfiguration.confidence.toFixed(2)} confidence`); // Step 3: Cache the combined results if (fullDetectionConfig.enableCaching) { try { await this.cacheManager.store(cacheKey, this.databaseUrl, this.schemaHash, detectionResults, autoConfiguration); logger_1.Logger.debug('Combined detection and auto-configuration results cached successfully'); } catch (error) { logger_1.Logger.debug('Failed to cache combined results:', error.message); // Continue without caching } } const totalTime = Date.now() - startTime; logger_1.Logger.success(`๐ŸŽ‰ Unified detection with auto-configuration completed in ${totalTime}ms`); return { detection: detectionResults, autoConfiguration }; } catch (error) { logger_1.Logger.error('Unified detection with auto-configuration failed:', error); throw new Error(`Unified detection with auto-configuration failed: ${error.message}`); } } /** * Perform unified detection across all systems */ async performUnifiedDetection(config = {}) { const fullConfig = { enableCrossValidation: true, enableConflictResolution: true, maxExecutionTime: 30000, // 30 seconds enableCaching: true, confidenceThreshold: 0.6, ...config }; const startTime = Date.now(); logger_1.Logger.info('๐Ÿ”„ Starting unified detection across all systems...'); // Check cache first if enabled let cacheKey; if (fullConfig.enableCaching) { try { // Generate schema hash for cache validation if (!this.schemaHash) { this.schemaHash = await detection_cache_1.DetectionCacheUtils.generateSchemaHash(this.client); } cacheKey = this.cacheManager.generateCacheKey(this.databaseUrl, this.schemaHash, fullConfig); const cachedEntry = await this.cacheManager.retrieve(cacheKey, this.databaseUrl, this.schemaHash); if (cachedEntry) { logger_1.Logger.info('๐Ÿ“ฆ Using cached unified detection result'); logger_1.Logger.debug(`Cache hit with confidence: ${cachedEntry.detectionResults.integration.overallConfidence}`); return cachedEntry.detectionResults; } } catch (error) { logger_1.Logger.debug('Cache lookup failed:', error.message); // Continue with fresh detection } } try { // Step 1: Schema Introspection (foundational data) const schemaStartTime = Date.now(); logger_1.Logger.debug('๐Ÿ” Performing schema introspection...'); const schemaResult = await this.schemaIntrospector.introspectSchema(); const schemaTime = Date.now() - schemaStartTime; logger_1.Logger.success(`โœ… Schema introspection completed in ${schemaTime}ms`); // Step 2: Framework Detection (leverages schema data) const frameworkStartTime = Date.now(); logger_1.Logger.debug('๐Ÿ—๏ธ Performing framework detection...'); const frameworkResult = await this.makerKitDetector.detectMakerKit({ tables: schemaResult.tables.map(t => ({ name: t.name, columns: t.columns.map(c => ({ name: c.name, type: c.type, nullable: c.isNullable })), relationships: [] })), functions: [], // Would be populated from actual schema constraints: schemaResult.constraints.dataIntegrityRules.map(r => ({ name: r.rule, table: r.table, type: this.mapConstraintTypeToFramework(r.type), definition: r.sqlCondition })), triggers: [] // Would be populated from actual schema }); const frameworkTime = Date.now() - frameworkStartTime; logger_1.Logger.success(`โœ… Framework detection completed in ${frameworkTime}ms`); // Step 3: Architecture Detection (new system) const architectureStartTime = Date.now(); logger_1.Logger.debug('๐Ÿ›๏ธ Performing architecture detection...'); const detectionContext = this.buildDetectionContext(schemaResult, frameworkResult); const architectureResult = await this.architectureDetector.detectArchitecture(detectionContext, fullConfig.architecture); const architectureTime = Date.now() - architectureStartTime; logger_1.Logger.success(`โœ… Architecture detection completed in ${architectureTime}ms`); // Step 4: Domain Detection (new system) const domainStartTime = Date.now(); logger_1.Logger.debug('๐ŸŽฏ Performing domain detection...'); const domainContext = this.buildDomainContext(schemaResult, frameworkResult, architectureResult); const domainResult = await this.domainDetector.detectDomain(domainContext, fullConfig.domain); const domainTime = Date.now() - domainStartTime; logger_1.Logger.success(`โœ… Domain detection completed in ${domainTime}ms`); // Step 5: Cross-validation and integration const crossValidation = fullConfig.enableCrossValidation ? this.performCrossValidation(schemaResult, frameworkResult, architectureResult, domainResult) : this.createEmptyCrossValidation(); // Step 6: Conflict detection and resolution const conflicts = fullConfig.enableConflictResolution ? this.detectAndResolveConflicts(schemaResult, frameworkResult, architectureResult, domainResult) : []; // Step 7: Generate consolidated recommendations const recommendations = this.generateConsolidatedRecommendations(schemaResult, frameworkResult, architectureResult, domainResult, crossValidation, conflicts); // Step 8: Calculate overall confidence const overallConfidence = this.calculateOverallConfidence(schemaResult, frameworkResult, architectureResult, domainResult, crossValidation); const totalTime = Date.now() - startTime; const unifiedResult = { architecture: architectureResult, domain: domainResult, schema: schemaResult, framework: frameworkResult, integration: { overallConfidence, crossValidation, recommendations, conflicts, warnings: this.generateIntegrationWarnings(architectureResult, domainResult, schemaResult, frameworkResult), performance: { totalExecutionTime: totalTime, schemaIntrospectionTime: schemaTime, frameworkDetectionTime: frameworkTime, architectureDetectionTime: architectureTime, domainDetectionTime: domainTime } } }; // Cache the result if enabled if (fullConfig.enableCaching) { try { await this.cacheManager.store(cacheKey, this.databaseUrl, this.schemaHash, unifiedResult, undefined, // No auto-configuration at this level undefined // Use default TTL ); logger_1.Logger.debug('Detection results cached successfully'); } catch (error) { logger_1.Logger.debug('Failed to cache detection results:', error.message); // Continue without caching } } logger_1.Logger.success(`๐ŸŽ‰ Unified detection completed in ${totalTime}ms with ${overallConfidence.toFixed(2)} confidence`); return unifiedResult; } catch (error) { logger_1.Logger.error('Unified detection failed:', error); throw new Error(`Unified detection failed: ${error.message}`); } } /** * Build detection context from existing introspection results */ buildDetectionContext(schemaResult, frameworkResult) { return { schema: { tableCount: schemaResult.tables.length, tableNames: schemaResult.tables.map(t => t.name), relationships: schemaResult.relationships.map(r => ({ fromTable: r.fromTable, toTable: r.toTable, type: r.relationshipType, columnName: r.fromColumn })), constraints: schemaResult.constraints.dataIntegrityRules.map(r => ({ tableName: r.table, constraintName: r.rule, type: this.mapConstraintType(r.type) })) }, framework: { type: frameworkResult.isMakerKit ? 'makerkit' : 'unknown', version: frameworkResult.version, confidence: frameworkResult.confidence }, businessLogic: { functions: [], triggers: [], policies: [] }, existingResults: { frameworkDetection: frameworkResult, multiTenantDetection: undefined, businessLogicAnalysis: undefined } }; } /** * Build domain analysis context from existing results */ buildDomainContext(schemaResult, frameworkResult, architectureResult) { const baseContext = this.buildDetectionContext(schemaResult, frameworkResult); return { ...baseContext, domainHints: { suggestedDomains: this.suggestDomainsFromArchitecture(architectureResult.architectureType), excludedDomains: [], knownPatterns: [] } }; } /** * Suggest likely domains based on architecture type */ suggestDomainsFromArchitecture(architectureType) { switch (architectureType) { case 'individual': return ['outdoor', 'social', 'generic']; // Individual creators often in outdoor/social case 'team': return ['saas', 'ecommerce', 'generic']; // Teams often in business/enterprise case 'hybrid': return ['saas', 'ecommerce', 'social', 'generic']; // Hybrid can be anything default: return ['generic']; } } /** * Perform cross-validation between different detection systems */ performCrossValidation(schemaResult, frameworkResult, architectureResult, domainResult) { const agreements = []; const disagreements = []; // Validate architecture against framework const architectureFrameworkAgreement = this.validateArchitectureFrameworkAgreement(architectureResult, frameworkResult, agreements, disagreements); // Validate architecture against schema patterns const schemaArchitectureAgreement = this.validateSchemaArchitectureAgreement(schemaResult, architectureResult, agreements, disagreements); // Validate domain against architecture alignment const domainArchitectureAgreement = this.validateDomainArchitectureAgreement(domainResult, architectureResult, agreements, disagreements); const overallAgreement = (architectureFrameworkAgreement + schemaArchitectureAgreement + domainArchitectureAgreement) / 3; return { architectureFrameworkAgreement, schemaArchitectureAgreement, domainArchitectureAgreement, overallAgreement, agreements, disagreements, engineAgreement: { 'architecture-framework': architectureFrameworkAgreement, 'schema-architecture': schemaArchitectureAgreement, 'domain-architecture': domainArchitectureAgreement } }; } /** * Validate agreement between architecture and framework detection */ validateArchitectureFrameworkAgreement(architectureResult, frameworkResult, agreements, disagreements) { let agreementScore = 0; let totalChecks = 0; // Check if MakerKit detection aligns with architecture type if (frameworkResult.isMakerKit) { totalChecks++; // MakerKit typically supports team and hybrid architectures if (architectureResult.architectureType === 'team' || architectureResult.architectureType === 'hybrid') { agreementScore++; agreements.push('MakerKit framework aligns with team/hybrid architecture'); } else { disagreements.push('MakerKit framework detected but architecture appears individual-focused'); } } // Check MakerKit version alignment if (frameworkResult.version) { totalChecks++; const hasComplexFeatures = architectureResult.platformFeatures.some(f => f.category === 'organization' || f.category === 'collaboration'); if (frameworkResult.version === 'v3' && hasComplexFeatures) { agreementScore++; agreements.push('MakerKit v3 aligns with complex organizational features'); } else if (frameworkResult.version === 'v2' && !hasComplexFeatures) { agreementScore++; agreements.push('MakerKit v2 aligns with simpler feature set'); } else { disagreements.push(`MakerKit ${frameworkResult.version} features don't match detected complexity`); } } return totalChecks > 0 ? agreementScore / totalChecks : 0.5; } /** * Validate agreement between schema patterns and architecture detection */ validateSchemaArchitectureAgreement(schemaResult, architectureResult, agreements, disagreements) { let agreementScore = 0; let totalChecks = 0; // Check table patterns alignment const userTables = schemaResult.patterns.filter(p => p.suggestedRole === 'user'); const contentTables = schemaResult.patterns.filter(p => p.suggestedRole === 'content'); totalChecks++; if (architectureResult.architectureType === 'individual') { if (userTables.length === 1 && contentTables.length > 0) { agreementScore++; agreements.push('Schema patterns align with individual architecture'); } else { disagreements.push('Individual architecture but schema suggests multiple user patterns'); } } else if (architectureResult.architectureType === 'team') { if (schemaResult.tables.some(t => t.name.includes('organization') || t.name.includes('team'))) { agreementScore++; agreements.push('Schema contains team/organization tables matching team architecture'); } else { disagreements.push('Team architecture but schema lacks team-oriented tables'); } } // Check relationship complexity totalChecks++; const relationshipCount = schemaResult.relationships.length; const expectedComplexity = this.getExpectedRelationshipComplexity(architectureResult.architectureType); if (relationshipCount >= expectedComplexity.min && relationshipCount <= expectedComplexity.max) { agreementScore++; agreements.push(`Relationship complexity (${relationshipCount}) matches ${architectureResult.architectureType} architecture`); } else { disagreements.push(`Relationship complexity (${relationshipCount}) doesn't match expected range for ${architectureResult.architectureType}`); } return totalChecks > 0 ? agreementScore / totalChecks : 0.5; } /** * Validate agreement between domain and architecture detection */ validateDomainArchitectureAgreement(domainResult, architectureResult, agreements, disagreements) { let agreementScore = 0; let totalChecks = 0; // Check domain-architecture typical alignments totalChecks++; const domainArchitectureAlignment = this.getDomainArchitectureAlignment(domainResult.primaryDomain, architectureResult.architectureType); if (domainArchitectureAlignment >= 0.7) { agreementScore++; agreements.push(`${domainResult.primaryDomain} domain aligns well with ${architectureResult.architectureType} architecture`); } else if (domainArchitectureAlignment < 0.3) { disagreements.push(`${domainResult.primaryDomain} domain typically doesn't align with ${architectureResult.architectureType} architecture`); } // Check confidence alignment totalChecks++; const confidenceDiff = Math.abs(domainResult.confidence - architectureResult.confidence); if (confidenceDiff < 0.2) { agreementScore++; agreements.push('Domain and architecture detection confidence levels are aligned'); } else { disagreements.push(`Large confidence difference between domain (${domainResult.confidence.toFixed(2)}) and architecture (${architectureResult.confidence.toFixed(2)})`); } // Check hybrid capabilities alignment if (domainResult.hybridCapabilities && architectureResult.architectureType === 'hybrid') { totalChecks++; agreementScore++; agreements.push('Hybrid domain capabilities align with hybrid architecture'); } else if (domainResult.hybridCapabilities && architectureResult.architectureType !== 'hybrid') { totalChecks++; disagreements.push('Hybrid domain capabilities detected but architecture is not hybrid'); } return totalChecks > 0 ? agreementScore / totalChecks : 0.5; } /** * Get alignment score between domain and architecture types */ getDomainArchitectureAlignment(domain, architecture) { const alignmentMatrix = { outdoor: { individual: 0.9, team: 0.3, hybrid: 0.7 }, saas: { individual: 0.2, team: 0.9, hybrid: 0.8 }, ecommerce: { individual: 0.4, team: 0.7, hybrid: 0.9 }, social: { individual: 0.8, team: 0.6, hybrid: 0.7 }, generic: { individual: 0.5, team: 0.5, hybrid: 0.5 } }; return alignmentMatrix[domain]?.[architecture] ?? 0.5; } /** * Detect and resolve conflicts between detection systems */ detectAndResolveConflicts(schemaResult, frameworkResult, architectureResult, domainResult) { const conflicts = []; // Check for architecture-framework conflicts if (frameworkResult.isMakerKit && frameworkResult.confidence > 0.7) { if (architectureResult.architectureType === 'individual' && architectureResult.confidence > 0.7) { conflicts.push({ type: 'architecture_mismatch', description: 'High confidence MakerKit detection conflicts with individual architecture', severity: 'medium', suggestedResolution: 'Consider hybrid architecture or verify MakerKit configuration', involvedSystems: ['architecture', 'framework'] }); } } // Check for schema-architecture conflicts const teamTables = schemaResult.tables.filter(t => t.name.includes('team') || t.name.includes('organization') || t.name.includes('workspace')); if (teamTables.length > 0 && architectureResult.architectureType === 'individual') { conflicts.push({ type: 'schema_inconsistency', description: 'Schema contains team-oriented tables but architecture is individual', severity: 'high', suggestedResolution: 'Re-evaluate architecture detection or check for hybrid patterns', involvedSystems: ['schema', 'architecture'] }); } // Check for domain-architecture alignment conflicts if (domainResult.primaryDomain === 'outdoor' && architectureResult.architectureType === 'team') { if (domainResult.confidence > 0.7 && architectureResult.confidence > 0.7) { conflicts.push({ type: 'architecture_mismatch', description: 'Outdoor domain typically uses individual/hybrid architecture but team architecture detected', severity: 'medium', suggestedResolution: 'Verify if this is a team-oriented outdoor platform or consider hybrid architecture', involvedSystems: ['architecture', 'domain'] }); } } // Check for domain-specific feature conflicts if (domainResult.primaryDomain === 'saas' && !teamTables.length) { if (domainResult.confidence > 0.7) { conflicts.push({ type: 'schema_inconsistency', description: 'SaaS domain detected but schema lacks typical team/organization structures', severity: 'medium', suggestedResolution: 'Verify SaaS classification or check for alternative team management patterns', involvedSystems: ['schema', 'domain'] }); } } // Check for low confidence across all systems (including domain) if (schemaResult.framework.confidence < 0.5 && frameworkResult.confidence < 0.5 && architectureResult.confidence < 0.5 && domainResult.confidence < 0.5) { conflicts.push({ type: 'framework_mismatch', description: 'Low confidence across all detection systems including domain detection', severity: 'high', suggestedResolution: 'Manual verification required - consider custom configuration and domain specification', involvedSystems: ['schema', 'framework', 'architecture', 'domain'] }); } return conflicts; } /** * Generate consolidated recommendations from all systems */ generateConsolidatedRecommendations(schemaResult, frameworkResult, architectureResult, domainResult, crossValidation, conflicts) { const recommendations = []; // Architecture-specific recommendations recommendations.push(`Platform Architecture: ${architectureResult.architectureType} (${(architectureResult.confidence * 100).toFixed(0)}% confidence)`); recommendations.push(...architectureResult.recommendations); // Domain-specific recommendations recommendations.push(`Content Domain: ${domainResult.primaryDomain} (${(domainResult.confidence * 100).toFixed(0)}% confidence)`); if (domainResult.secondaryDomains.length > 0) { const secondaryDomainsList = domainResult.secondaryDomains .map(d => `${d.domain}(${(d.confidence * 100).toFixed(0)}%)`) .join(', '); recommendations.push(`Secondary domains: ${secondaryDomainsList}`); } if (domainResult.hybridCapabilities) { recommendations.push('โœจ Platform shows hybrid domain capabilities - consider multi-domain strategies'); } recommendations.push(...domainResult.reasoning.slice(0, 3)); // Top 3 domain reasoning points // Framework-specific recommendations if (frameworkResult.isMakerKit) { recommendations.push(`Framework: MakerKit ${frameworkResult.version || 'detected'} (${(frameworkResult.confidence * 100).toFixed(0)}% confidence)`); recommendations.push(...frameworkResult.recommendations); } // Schema-specific recommendations recommendations.push(...schemaResult.recommendations.map(r => `Schema: ${r.message}`)); // Cross-validation recommendations if (crossValidation.overallAgreement < 0.7) { recommendations.push('โš ๏ธ Low cross-validation agreement - consider manual review'); } if (crossValidation.disagreements.length > 0) { recommendations.push('๐Ÿ“ Review disagreements between detection systems'); } // Conflict-based recommendations for (const conflict of conflicts) { if (conflict.severity === 'high') { recommendations.push(`๐Ÿšจ High Priority: ${conflict.suggestedResolution}`); } else { recommendations.push(`โš ๏ธ ${conflict.suggestedResolution}`); } } // Performance recommendations if (architectureResult.detectionMetrics.executionTime > 10000) { recommendations.push('โฑ๏ธ Consider using faster detection strategy for better performance'); } return Array.from(new Set(recommendations)); // Remove duplicates } /** * Calculate overall confidence across all detection systems */ calculateOverallConfidence(schemaResult, frameworkResult, architectureResult, domainResult, crossValidation) { // Weight different confidence scores including domain detection const weights = { schema: 0.15, framework: 0.25, architecture: 0.25, domain: 0.20, crossValidation: 0.15 }; const weightedSum = (schemaResult.framework.confidence * weights.schema) + (frameworkResult.confidence * weights.framework) + (architectureResult.confidence * weights.architecture) + (domainResult.confidence * weights.domain) + (crossValidation.overallAgreement * weights.crossValidation); return Math.min(1.0, weightedSum); } /** * Helper methods */ createEmptyCrossValidation() { return { architectureFrameworkAgreement: 0.5, schemaArchitectureAgreement: 0.5, domainArchitectureAgreement: 0.5, overallAgreement: 0.5, agreements: [], disagreements: [], engineAgreement: { 'architecture-framework': 0.5, 'schema-architecture': 0.5, 'domain-architecture': 0.5 } }; } mapConstraintType(type) { const mapping = { 'required_relationship': 'foreign_key', 'conditional_insert': 'check', 'value_constraint': 'check', 'business_rule': 'trigger' }; return mapping[type] || type; } mapConstraintTypeToFramework(type) { const mapping = { 'required_relationship': 'foreign_key', 'conditional_insert': 'check', 'value_constraint': 'check', 'business_rule': 'check' }; return mapping[type] || 'check'; } getExpectedRelationshipComplexity(architectureType) { switch (architectureType) { case 'individual': return { min: 2, max: 8 }; case 'team': return { min: 8, max: 20 }; case 'hybrid': return { min: 6, max: 25 }; default: return { min: 0, max: 100 }; } } /** * Extract database URL from Supabase client */ extractUrlFromClient(client) { try { // Try to extract URL from client properties return client.supabaseUrl || 'unknown-url'; } catch { return 'unknown-url'; } } /** * Clear detection cache */ async clearCache() { await this.cacheManager.clear(); this.schemaHash = undefined; // Force regeneration logger_1.Logger.info('Detection cache cleared'); } /** * Get cache statistics */ async getCacheStatistics() { return await this.cacheManager.getStatistics(); } generateCacheKey(config) { return `unified_detection_${JSON.stringify(config)}`; } /** * Clear all detection caches */ async clearCaches() { await this.cacheManager.clear(); this.schemaIntrospector.clearCache(); logger_1.Logger.info('๐Ÿงน All detection caches cleared'); } /** * Get quick detection summary for performance-critical scenarios */ async getQuickDetectionSummary() { const startTime = Date.now(); // Use cached schema introspection if available let schemaResult = this.schemaIntrospector.getCachedResult(); if (!schemaResult) { schemaResult = await this.schemaIntrospector.introspectSchema(); } // Quick architecture detection with fast strategy const detectionContext = this.buildDetectionContext(schemaResult, { isMakerKit: false, confidence: 0, detectedFeatures: [], missingFeatures: [], recommendations: [] }); const architectureResult = await this.architectureDetector.detectArchitecture(detectionContext, { strategy: 'fast', maxExecutionTime: 5000 }); const executionTime = Date.now() - startTime; return { architectureType: architectureResult.architectureType, confidence: architectureResult.confidence, isFrameworkDetected: schemaResult.framework.confidence > 0.5, executionTime }; } /** * Generate integration warnings based on detection results */ generateIntegrationWarnings(architectureResult, domainResult, schemaResult, frameworkResult) { const warnings = []; // Low confidence warnings if (architectureResult.confidence < 0.6) { warnings.push('Low confidence in architecture detection - results may be inaccurate'); } if (domainResult.confidence < 0.6) { warnings.push('Low confidence in domain detection - results may be inaccurate'); } if (frameworkResult.confidence < 0.6) { warnings.push('Low confidence in framework detection - results may be inaccurate'); } // Integration consistency warnings const hasArchitectureWarnings = architectureResult.warnings?.length > 0; const hasDomainWarnings = domainResult.warnings?.length > 0; if (hasArchitectureWarnings && hasDomainWarnings) { warnings.push('Multiple detection systems reported warnings - consider manual verification'); } // Framework mismatch warnings if (schemaResult.framework.framework !== frameworkResult.framework && frameworkResult.confidence > 0.7) { warnings.push('Schema and framework detection results differ - verify framework configuration'); } return warnings; } } exports.DetectionIntegrationEngine = DetectionIntegrationEngine; /** * Default configuration for unified detection */ exports.DEFAULT_UNIFIED_DETECTION_CONFIG = { enableCrossValidation: true, enableConflictResolution: true, maxExecutionTime: 30000, enableCaching: true, confidenceThreshold: 0.6, architecture: { strategy: 'comprehensive', confidenceThreshold: 0.6, includeDetailedEvidence: true, analyzeBusinessLogic: false, analyzeRLSPolicies: false, deepRelationshipAnalysis: true, maxExecutionTime: 15000, useCaching: true } }; //# sourceMappingURL=detection-integration.js.map