Spaces:
Paused
Paused
Deploy from GitHub Actions 2025-12-16_04-55-23
Browse filesFiles changed (5)
170 unmodified lines1711721731741751761771049 unmodified lines122712281229123012311232123312341235123612371238123912401241124212431244124512461247170 unmodified lines// Cloud defaults like 7860 break the internal reflex arc.const PORT = 3001;// Start server IMMEDIATELYserver.listen(PORT, '0.0.0.0', () => {console.log(`🚀 Backend server running on http://0.0.0.0:${PORT}`);console.log(`📡 MCP WebSocket available at ws://0.0.0.0:${PORT}/mcp/ws`);1049 unmodified lines* GET /api/evolution/graph/stats* Get Neo4j graph statistics for 3D visualization* 🔗 NEURAL LINK ENDPOINT*/app.get('/api/evolution/graph/stats', async (_req, res) => {try {const { neo4jService } = await import('./database/Neo4jService.js');// 1. Fetch Statsconst statsQuery = `MATCH (n)OPTIONAL MATCH ()-[r]->()RETURN count(DISTINCT n) as nodes, count(DISTINCT r) as relationships`;const statsResult = await neo4jService.runQuery(statsQuery);const stats = {nodes: statsResult[0]?.nodes?.toNumber ? statsResult[0].nodes.toNumber() : (statsResult[0]?.nodes || 0),relationships: statsResult[0]?.relationships?.toNumber ? statsResult[0].relationships.toNumber() : (statsResult[0]?.relationships || 0)};// 2. Fetch Sample Nodes for Visualization170 unmodified lines1711721731741751761049 unmodified lines12261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254170 unmodified lines// Cloud defaults like 7860 break the internal reflex arc.const PORT = 3001;server.listen(PORT, '0.0.0.0', () => {console.log(`🚀 Backend server running on http://0.0.0.0:${PORT}`);console.log(`📡 MCP WebSocket available at ws://0.0.0.0:${PORT}/mcp/ws`);1049 unmodified lines* GET /api/evolution/graph/stats* Get Neo4j graph statistics for 3D visualization* 🔗 NEURAL LINK ENDPOINT** OPTIMIZED: Uses separate lightweight queries to avoid memory overflow* on Neo4j AuraDB free tier (824 MiB limit)*/app.get('/api/evolution/graph/stats', async (_req, res) => {try {const { neo4jService } = await import('./database/Neo4jService.js');// 1. Fetch Stats using memory-efficient separate queries// Note: The original MATCH (n) OPTIONAL MATCH ()-[r]->() creates a cross-product// that exceeds Neo4j AuraDB's memory limits on large graphs (150K+ nodes)const nodeCountQuery = `MATCH (n) RETURN count(n) as nodes`;const relCountQuery = `MATCH ()-[r]->() RETURN count(r) as relationships`;// Run queries in parallel for better performanceconst [nodeResult, relResult] = await Promise.all([neo4jService.runQuery(nodeCountQuery),neo4jService.runQuery(relCountQuery)]);const stats = {nodes: nodeResult[0]?.nodes?.toNumber ? nodeResult[0].nodes.toNumber() : (nodeResult[0]?.nodes || 0),relationships: relResult[0]?.relationships?.toNumber ? relResult[0].relationships.toNumber() : (relResult[0]?.relationships || 0)};// 2. Fetch Sample Nodes for Visualization
1470 unmodified lines14711472147314741475147614771470 unmodified linesbreak;case 'backend':const backendResponse = await fetch('http://localhost:3001/api/health', {signal: AbortSignal.timeout(5000)});success = backendResponse.ok;1470 unmodified lines147114721473147414751476147714781470 unmodified linesbreak;case 'backend':const backendPort = process.env.PORT || 7860;const backendResponse = await fetch(`http://localhost:${backendPort}/api/health`, {signal: AbortSignal.timeout(5000)});success = backendResponse.ok;
32 unmodified lines333435363738519 unmodified lines558559560561562563564565143 unmodified lines7097107117127137147154 unmodified lines7207217227237247257264 unmodified lines73173273373473573673732 unmodified linesconst log = logger.child({ module: 'CognitiveErrorIntelligence' });// ═══════════════════════════════════════════════════════════════════════════// TYPES// ═══════════════════════════════════════════════════════════════════════════519 unmodified lines});});} else if (action.apiCall) {// Execute API callconst response = await fetch(action.apiCall.endpoint, {method: action.apiCall.method,headers: { 'Content-Type': 'application/json' },body: action.apiCall.body ? JSON.stringify(action.apiCall.body) : undefined143 unmodified linesname: 'Restart Redis Connection',description: 'Reconnect to Redis when connection is lost',errorPatterns: ['ECONNREFUSED', 'redis', 'connection refused'],apiCall: { endpoint: 'http://localhost:3001/api/healing/service/redis', method: 'POST' },requiresApproval: false,riskLevel: 'low',successRate: 0.85,4 unmodified linesname: 'Clear Memory Cache',description: 'Clear in-memory caches when memory is low',errorPatterns: ['heap', 'memory', 'OOM'],apiCall: { endpoint: 'http://localhost:3001/api/system/clear-cache', method: 'POST' },requiresApproval: false,riskLevel: 'low',successRate: 0.9,4 unmodified linesname: 'Retry Database Connection',description: 'Attempt to reconnect to database',errorPatterns: ['database', 'postgres', 'neo4j', 'SQLSTATE'],apiCall: { endpoint: 'http://localhost:3001/api/healing/service/database', method: 'POST' },requiresApproval: false,riskLevel: 'medium',successRate: 0.75,32 unmodified lines333435363738394041519 unmodified lines561562563564565566567568569570571143 unmodified lines7157167177187197207214 unmodified lines7267277287297307317324 unmodified lines73773873974074174274332 unmodified linesconst log = logger.child({ module: 'CognitiveErrorIntelligence' });// Dynamic base URL for self-healing API callsconst getBaseUrl = () => `http://localhost:${process.env.PORT || 7860}`;// ═══════════════════════════════════════════════════════════════════════════// TYPES// ═══════════════════════════════════════════════════════════════════════════519 unmodified lines});});} else if (action.apiCall) {// Execute API call - prepend base URL to relative pathsconst endpoint = action.apiCall.endpoint.startsWith('/')? `${getBaseUrl()}${action.apiCall.endpoint}`: action.apiCall.endpoint;const response = await fetch(endpoint, {method: action.apiCall.method,headers: { 'Content-Type': 'application/json' },body: action.apiCall.body ? JSON.stringify(action.apiCall.body) : undefined143 unmodified linesname: 'Restart Redis Connection',description: 'Reconnect to Redis when connection is lost',errorPatterns: ['ECONNREFUSED', 'redis', 'connection refused'],apiCall: { endpoint: '/api/healing/service/redis', method: 'POST' },requiresApproval: false,riskLevel: 'low',successRate: 0.85,4 unmodified linesname: 'Clear Memory Cache',description: 'Clear in-memory caches when memory is low',errorPatterns: ['heap', 'memory', 'OOM'],apiCall: { endpoint: '/api/system/clear-cache', method: 'POST' },requiresApproval: false,riskLevel: 'low',successRate: 0.9,4 unmodified linesname: 'Retry Database Connection',description: 'Attempt to reconnect to database',errorPatterns: ['database', 'postgres', 'neo4j', 'SQLSTATE'],apiCall: { endpoint: '/api/healing/service/database', method: 'POST' },requiresApproval: false,riskLevel: 'medium',successRate: 0.75,
248 unmodified lines24925025125225325425525625725825926026126226326426566 unmodified lines332333334335336337338248 unmodified linestry {if (this.neo4jAdapter) {// Get current graph statsconst statsResult = await this.neo4jAdapter.runQuery(`MATCH (n)WITH count(n) as nodeCountMATCH ()-[r]->()RETURN nodeCount, count(r) as relCount`);const stats = statsResult?.[0];const nodeCount = stats?.nodeCount || 0;const relCount = stats?.relCount || 0;// Create evolution event nodeawait this.neo4jAdapter.runQuery(`66 unmodified linestry {// Trigger compilation via HTTP to selfconst port = process.env.PORT || 3001;const response = await fetch(`http://localhost:${port}/api/knowledge/compile`, {method: 'POST',headers: { 'Content-Type': 'application/json' }248 unmodified lines24925025125225325425525625725825926026126226366 unmodified lines330331332333334335336248 unmodified linestry {if (this.neo4jAdapter) {// Get current graph stats - use separate queries to avoid memory overflow// on Neo4j AuraDB free tier (824 MiB limit with 150K+ nodes)const [nodeResult, relResult] = await Promise.all([this.neo4jAdapter.runQuery(`MATCH (n) RETURN count(n) as nodeCount`),this.neo4jAdapter.runQuery(`MATCH ()-[r]->() RETURN count(r) as relCount`)]);const nodeCount = nodeResult?.[0]?.nodeCount || 0;const relCount = relResult?.[0]?.relCount || 0;// Create evolution event nodeawait this.neo4jAdapter.runQuery(`66 unmodified linestry {// Trigger compilation via HTTP to selfconst port = process.env.PORT || 7860;const response = await fetch(`http://localhost:${port}/api/knowledge/compile`, {method: 'POST',headers: { 'Content-Type': 'application/json' }
98 unmodified lines99100101102103104135 unmodified lines24024124224324424524628 unmodified lines275276277278279280281282122 unmodified lines40540640740840941041198 unmodified lineseventBus.on('threat:detected', () => {this.healthMetrics.lastIngestion = new Date();});eventBus.on('system:heartbeat', (data: any) => {135 unmodified linestry {// Check if MCP tools endpoint responds (indicates server is ready)const port = process.env.PORT || 3001;const baseUrl = process.env.API_BASE_URL || `http://localhost:${port}`;const response = await fetch(`${baseUrl}/api/mcp/tools`, {method: 'GET',28 unmodified linesconst name = 'apiEndpoints';try {// Test key API endpoints (use port 3001 where backend runs)const port = process.env.PORT || 3001;const baseUrl = process.env.API_BASE_URL || `http://localhost:${port}`;const endpoints = [{ url: `${baseUrl}/health`, method: 'GET' },122 unmodified lineslogger.info(' → API endpoints unreachable - checking backend status...');fixAction = 'Health check on correct backend port';try {const backendPort = process.env.PORT || '3001';const testUrl = `http://localhost:${backendPort}/health`;const response = await fetch(testUrl, { signal: AbortSignal.timeout(3000) });if (response.ok) {98 unmodified lines99100101102103104105106107108109110111135 unmodified lines24724824925025125225325428 unmodified lines283284285286287288289290122 unmodified lines41341441541641741841998 unmodified lineseventBus.on('threat:detected', () => {this.healthMetrics.lastIngestion = new Date();this.healthMetrics.dataflowOk = true;});// Also track threat feed broadcasts (from OpenPhish etc.)eventBus.on('threats:broadcast', () => {this.healthMetrics.lastIngestion = new Date();this.healthMetrics.dataflowOk = true;});eventBus.on('system:heartbeat', (data: any) => {135 unmodified linestry {// Check if MCP tools endpoint responds (indicates server is ready)// Default to 7860 which is the standard port for WidgeTDC backend (both local and HuggingFace)const port = process.env.PORT || 7860;const baseUrl = process.env.API_BASE_URL || `http://localhost:${port}`;const response = await fetch(`${baseUrl}/api/mcp/tools`, {method: 'GET',28 unmodified linesconst name = 'apiEndpoints';try {// Test key API endpoints - default to 7860 which is standard for WidgeTDCconst port = process.env.PORT || 7860;const baseUrl = process.env.API_BASE_URL || `http://localhost:${port}`;const endpoints = [{ url: `${baseUrl}/health`, method: 'GET' },122 unmodified lineslogger.info(' → API endpoints unreachable - checking backend status...');fixAction = 'Health check on correct backend port';try {const backendPort = process.env.PORT || '7860';const testUrl = `http://localhost:${backendPort}/health`;const response = await fetch(testUrl, { signal: AbortSignal.timeout(3000) });if (response.ok) {
apps/backend/src/index.ts+17-10
apps/backend/src/mcp/servers/NeuralBridgeServer.ts+2-1
apps/backend/src/services/CognitiveErrorIntelligence.ts+11-5
apps/backend/src/services/NudgeService.ts+10-12
apps/backend/src/services/agent/HansPedderAgentController.ts+12-4